我正在尝试在React Native应用程序中实现PubNub。这个想法是在后台运行PubNub,以便每30秒钟在特定频道中更新一次用户的位置。
这是我的代码。这是我App.js中的导出默认功能:
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>
);
}
我担心这段代码有两件事:
CANCELLED Location cancelled by another request
。我不太确定它来自哪里,也许它来自GetLocation.getCurrentPosition,所以它可能与PubNub无关。所以我的问题是:我是否使用正确的方法在React Native中使用PubNub?如果没有,我该怎么做才能使它更好?