我有一个React Native应用程序,我试图获得一个发送到
JavaScript处理程序的静默iOS推送通知.
我看到的行为是AppDelegate中的didReceiveRemoteNotification函数被调用,但是我的JavaScript中的处理程序不会被调用,除非应用程序在前台,或者最近才被关闭.
我很困惑的事情显然是应用程序正在被唤醒,并且它的didReceiveRemoteNotification函数被调用,但是然后调用[RCTPushnotificationmanager didReceiveRemoteNotification:notification]似乎没有任何作用.
另外,如果我在收到通知后打开应用程序,那么我看到React Native处理程序在这一点被调用.
我的didReceiveRemoteNotification功能如下所示:
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)notification { NSLog(@"didReceiveRemoteNotification"); [RCTPushnotificationmanager didReceiveRemoteNotification:notification]; }
在我的React Native应用程序的Root组件中,我有:
componentDidMount() { AppState.addEventListener('change',this.handleAppStateChange); PushNotificationIOS.addEventListener('notification',(notification) => { console.log("notification recieved"); }) } handleAppStateChange(currentAppState) { console.log(currentAppState); }
我使用AWS SNS发送推送通知,并显示以下消息:
{ "APNS_SANDBox":"{\"aps\":{\"content-available\":\"1\"}}" }
这是XCode的日志:
2016-04-20 10:38:01.255 [info][tid:com.facebook.React.JavaScript] inactive 2016-04-20 10:38:01.986 [info][tid:com.facebook.React.JavaScript] background 2016-04-20 10:38:17.279 test[4056:1383261] didReceiveRemoteNotification 2016-04-20 10:38:17.284 [info][tid:com.facebook.React.JavaScript] notification recieved 2016-04-20 10:44:56.330 test[4056:1383261] didReceiveRemoteNotification 2016-04-20 10:44:56.332 [info][tid:com.facebook.React.JavaScript] notification recieved 2016-04-20 10:46:07.091 test[4056:1383261] didReceiveRemoteNotification 2016-04-20 10:49:30.039 [info][tid:com.facebook.React.JavaScript] notification recieved 2016-04-20 10:49:30.639 [info][tid:com.facebook.React.JavaScript] active
在此日志中,发送3个推送通知.在10:38和10:44收到的两个都正确地称为JavaScript.
但是,在10:46收到的那个没有在JavaScript中调用处理程序,直到我在10:49打开应用程序.
有什么我可以做的,以确保即使应用程序不运行,我的React Native代码的调用?
解决方法
为了在后台点击你的应用程序的通知,您还需要定义一个fetchCompletionHandler,其中包含完成处理函数,如下所示. aps:{content-available:1}有效载荷应该唤醒你的应用程序,并在你的AppDelegate中触发这个代码,然后在RN中命中你的JavaScript.
// fetch notifications in the background and foreground -(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)notification fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler { [RCTPushnotificationmanager didReceiveRemoteNotification:notification]; completionHandler(UIBackgroundFetchResultNewData); NSLog(@"Notification Body %@",notification); }