我使用 Expo 示例来获取设备的令牌:
async function registerForPushNotificationsAsync() {
let token;
if (Constants.isDevice) {
const { status: existingStatus } = await Notifications.getPermissionsAsync();
let finalStatus = existingStatus;
if (existingStatus !== 'granted') {
const { status } = await Notifications.requestPermissionsAsync();
finalStatus = status;
}
if (finalStatus !== 'granted') {
alert('Failed to get push token for push notification!');
return;
}
token = (await Notifications.getExpoPushTokenAsync()).data;
} else {
alert('Must use physical device for Push Notifications');
}
if (Platform.OS === 'android') {
Notifications.setNotificationChannelAsync('default', {
name: 'default',
importance: Notifications.AndroidImportance.MAX,
vibrationPattern: [0, 250, 250, 250],
lightColor: '#FF231F7C',
});
}
console.log("token -> ", token);
firebase.database().ref('users')
.child(firebase.auth().currentUser.uid)
.set({
expoToken: token
}, { merge: true });
return token;
}
useEffect(() => {
let subscriber;
firebase.auth().onAuthStateChanged((user) => {
if (user && !subscriber) {
registerForPushNotificationsAsync().then(token => setExpoPushToken(token));
subscriber = firebase.firestore()
.collection('users')
.doc(user.uid)
.onSnapshot(documentSnapshot => {
setUser(documentSnapshot.data())
})
}
})
return () => subscriber();
},[])
我在 useEffect()
中调用了我的函数并且我也在记录 Token
console.log("token -> ", token);
我收到两个日志
一个是令牌是 undefined
,然后它用 token
再次记录它。
问题是,我试图将令牌保存到 firebase:
firebase.database().ref('users')
.child(firebase.auth().currentUser.uid)
.set({
expoToken: token
}, { merge: true });
但我得到:
[Unhandled promise rejection: Error: Reference.set failed: second argument must be a valid function.]
我认为它试图保存令牌,但令牌在开始时未定义,然后它得到它。
答案 0 :(得分:1)
您可以先检查令牌是否未定义,然后再将其存储到 firestore。
if(token) {
firebase.database().ref('users')
.child(firebase.auth().currentUser.uid)
.set({
expoToken: token
}, { merge: true });
}