我提到this question获取设备令牌,以便向我的应用发送推送通知。我使用create-react-native-app
创建了我的应用。这是代码:
import React, { Component } from 'react';
import {
Platform,
StyleSheet,
AppRegistry,
Text,
View,
PushNotificationIOS
} from 'react-native';
type Props = {};
export default class Apptitude extends Component<Props> {
constructor() {
console.log('registering evt listerner in launchpad')
PushNotificationIOS.addEventLister('register', (token) => {
this.setState({
deviceToken: token
})
});
}
render() {
return (
<View>
</View>
);
}
}
PushNotificationIOS.addEventListener('registrationError', (registrationError) => {
console.lo('was error')
console.log(reason.message)
console.log(reason.code)
console.log(reason.details)
})
// yes I'm aware I've added an event listener in the constructor also. Neither of these callbacks fire
PushNotificationIOS.addEventListener('register', (token) => {
console.log('this is the token', token);
});
console.log('requesting permissions')
PushNotificationIOS.requestPermissions();
问题是register
和registrationError
事件从未触发过。我被提示批准权限,下次应用程序启动时,我可以使用checkPermissions()
并确认已授予权限。但是如果没有设备令牌,则无法向设备发送推送通知。我做错了什么?
答案 0 :(得分:1)
要注意的另一件事是,在模拟器上onRegister
功能未启用,您必须使用真实的设备。
答案 1 :(得分:0)
Xcode部分怎么样?
您应该在AppDelegate文件上导入TCTPushNotification
#import <React/RCTPushNotificationManager.h>
并实施以下代码以启用应用中的notification
和register
// Required to register for notifications
- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings
{
[RCTPushNotificationManager didRegisterUserNotificationSettings:notificationSettings];
}
// Required for the register event.
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
[RCTPushNotificationManager didRegisterForRemoteNotificationsWithDeviceToken:deviceToken];
}
// Required for the notification event. You must call the completion handler after handling the remote notification.
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{
[RCTPushNotificationManager didReceiveRemoteNotification:userInfo fetchCompletionHandler:completionHandler];
}
// Required for the registrationError event.
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
{
[RCTPushNotificationManager didFailToRegisterForRemoteNotificationsWithError:error];
}
// Required for the localNotification event.
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
{
[RCTPushNotificationManager didReceiveLocalNotification:notification];
}
有关更多信息,请使用官方文档
https://facebook.github.io/react-native/docs/pushnotificationios.html
答案 2 :(得分:0)
万一有人在真实设备上遇到过与我类似的问题,关键是要注册事件,但是在注册事件后专门调用PushNotificationIOS.requestPermissions();
。