我已在我的应用程序中实现了推送通知。
当我的应用程序在前台时,我的应用程序运行正常。
但是当应用程序在后台或被杀时,我的didReceiveRemoteNotification
会被调用两次。
我已经提出了一种处理推送通知并从didFinishLaunchingWithOptions
和didReceiveRemoteNotification
这是我的实施:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
NSDictionary *pushDictionary = [launchOptions valueForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
if (pushDictionary) {
[self customPushHandler:pushDictionary];
}
return YES;
}
并且:
- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo
fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))handler {
[self customPushHandler:userInfo];
}
并
- (void) customPushHandler:(NSDictionary *)notification {
// Code to push ViewController
NSLog(@"Push Notification"); //Got it two times when Clicked in notification banner
}
当我的应用程序运行时,ViewController被推送一次。当我打开我的应用程序从通知横幅,然后我的屏幕被推了两次。
我在customPushHandler
放置了一个NSLog,当App处于前台时,我得到了一次,当我从Notification banner中启动时,我得到了两次。
我的代码中有什么问题。?
答案 0 :(得分:3)
“ 当应用程序在后台运行时,该方法被调用两次,一次是在收到推送通知时,另一次是在您点击该通知时。”
您可以验证应用程序的状态,如果应用程序处于后台,则可以忽略收到的通知。
解决方案:Remote notification method called twice
快速4码:
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
if (application.applicationState == .background) {
completionHandler(.noData)
return
}
// logic
// call completionHandler with appropriate UIBackgroundFetchResult
}
答案 1 :(得分:0)
检查 didReceiveRemoteNotification 中的这一条件,例如如果您在app处于后台时点击通知。通过这种方式,您可以避免被调用两次。
- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo
fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))handler {
UIApplicationState state = [[UIApplication sharedApplication] applicationState];
if (state == UIApplicationStateBackground || state == UIApplicationStateInactive || state == UIApplicationStateForeground || state == UIApplicationStateActive)
{
//Do checking here.
[self customPushHandler:userInfo];
}
}
检查我编辑了我的答案。
答案 2 :(得分:0)
检查当前导航堆栈中的顶视图控制器,如:
if(![self.navigationController.topViewController isKindOfClass:[MyClass class]]) {
//code for pushing new controller
}
答案 3 :(得分:0)
每当您使用backgroundFetch进行远程通知时,请为其添加完成处理程序。
- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo
fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))handler {
[self customPushHandler:userInfo];
completionHandler(UIBackgroundFetchResultNewData)
}