我已经在我的应用程序中实现了推送通知。
当我的应用程序在前台时,我的应用程序运行正常。
但是当应用程序在后台或被杀死时,我的 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,一次当应用程序处于前台时我得到了它,两次当我从通知横幅启动它时得到它。
我的代码有什么问题?
最佳答案
“当应用程序在后台时,该方法会被调用两次,一次是在您收到推送通知时,另一次是在您点击该通知时。”
如果应用程序在后台,您可以验证应用程序状态并忽略收到的通知。
解决方案:Remote notification method called twice
swift 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
}
关于ios - didReceiveRemoteNotification 调用了两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34920273/