[英]didReceiveRemoteNotification called twice
我已經在我的應用程序中實現了推送通知。
當我的應用程序處於前台時,我的應用程序可以正常工作。
但是當應用程序在后台或被殺死時,我的didReceiveRemoteNotification
調用了兩次。
我已經創建了一個用於處理Push通知並從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將被推送一次。 當我從通知橫幅中打開我的應用程序時,我的屏幕將被按下兩次。
我將NSLog放置在customPushHandler
,一次是在App處於前台時,一次是從Notification橫幅啟動時。
我的代碼有什么問題?
“ 當應用程序在后台運行時,該方法被調用兩次,一次是在收到推送通知時,另一次是在點擊該通知時。 ”
您可以驗證應用程序狀態,如果應用程序處於后台,則可以忽略收到的通知。
解決方案: 兩次調用遠程通知方法
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
}
檢查didReceiveRemoteNotification中的這一條件,例如在應用程序處於后台時點擊通知 。 這樣,您可以避免兩次被調用。
- (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];
}
}
檢查我是否編輯了答案。
檢查當前導航堆棧中的頂視圖控制器,例如:
if(![self.navigationController.topViewController isKindOfClass:[MyClass class]]) {
//code for pushing new controller
}
每當您將backgroundFetch用於遠程通知時,都為此添加一個完成處理程序。
- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo
fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))handler {
[self customPushHandler:userInfo];
completionHandler(UIBackgroundFetchResultNewData)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.