如何解决如何在React Native中将PubNub与BackgroundTimer一起使用
我正在尝试在React Native应用程序中实现PubNub。这个想法是在后台运行PubNub,以便每30秒钟在特定频道中更新一次用户的位置。
export default function ponte() {
const [isLoading,setIsLoading] = React.useState(false);
const [user,setUser] = React.useState(null);
const [volunteerChannel,setVolunteerChannel] = React.useState(null);
// Handle user state changes
function onAuthStateChanged(user) {
setUser(user);
if (isLoading) setIsLoading(false);
}
if (isLoading) return null;
useEffect(() => {
SplashScreen.hide();
const subscriber = auth().onAuthStateChanged(onAuthStateChanged);
return subscriber; // unsubscribe on unmount
},[]);
const authContext = React.useMemo(() => {
return {
signIn: (email,password) =>
auth()
.signInWithEmailAndPassword(email.email,password.password)
.then(res => {
setIsLoading(false);
setUser(res.user.uid);
}),signUp: () => {
setIsLoading(false);
setUser("test");
},signOut: () => {
setIsLoading(false);
auth().signOut().then(() => console.log('User signed out!'));
setUser(null);
}
};
},[]);
BackgroundTimer.start();
BackgroundTimer.runBackgroundTimer(() => {
if(auth().currentUser && auth().currentUser.email /*&& !volunteerChannel*/) {
Promise.all([
fetch(API_URL + "/users?email=" + auth().currentUser.email)
])
.then(([res1]) => Promise.all([res1.json()]))
.then(([data1]) => {
if(data1[0].category === 'Voluntario') {
console.log('Volunteer channel: ' + data1[0].email);
GetLocation.getCurrentPosition({
enableHighAccuracy: true,timeout: 15000,})
.then(location => {
var pubnub = new PubNubReact({
publishKey: 'xxxx',subscribeKey: 'xxxx'
});
pubnub.publish({
message: {
latitude: location.latitude,longitude: location.longitude
},channel: data1[0].email
});
})
.catch(error => {
const { code,message } = error;
console.warn(code,message);
})
} else {
console.log(data1[0]);
}
})
.catch((error) => console.log(error))
}
},30000);
BackgroundTimer.stop();
return(
<AuthContext.Provider value={authContext}>
<NavigationContainer>
<RootStackScreen user={user} />
</NavigationContainer>
</AuthContext.Provider>
);
}
我担心这段代码有两件事:
- 第一个是注册的pubnub交易量:显然我有超过3.5K交易,我几乎没有在iOS模拟器中使用过该应用。
- 第二个是我收到警告:
CANCELLED Location cancelled by another request
。我不太确定它来自哪里,也许它来自GetLocation.getCurrentPosition,所以它可能与PubNub无关。
所以我的问题是:我是否使用正确的方法在React Native中使用PubNub?如果没有,我该怎么做才能使它更好?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。