iOS推送通知 - didReceiveRemoteNotification:fetchCompletionHandler:从未在前台调用

问题描述:

我在我的应用程序中实现了远程通知,但是我遇到了didReceiveRemoteNotification:fetchCompletionHandler:的问题。iOS推送通知 - didReceiveRemoteNotification:fetchCompletionHandler:从未在前台调用

当手机屏幕锁定时,我收到通知。如果用户滑动通知,则应用程序会回到前台并调用didReceiveRemoteNotification:fetchCompletionHandler:

但是,如果应用程序在前台运行,则永远不会调用didReceiveRemoteNotification:fetchCompletionHandler:。可能是什么原因?

我正在使用iOS 10.3.2

+1

尝试在其中放入警报并检查前景模式。 – Nirmalsinh

+0

看到这一次为ref https://stackoverflow.com/questions/39382852/didreceiveremotenotification-not-called-ios-10/39383027#39383027 –

+0

@mag_zbc假设你在iOS9上使用这种方法,而不是在ios10和UNUserNotificationCenter –

您正在使用哪个iOS版本?

有适用于iOS 9和iOS不同的方法10.

下面是iOS的10

//Called when a notification is delivered to a foreground app. 
    @available(iOS 10.0, *) 
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { 

    } 


    //Called to let your app know which action was selected by the user for a given notification. 
    @available(iOS 10.0, *) 
    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping() -> Void) { 

    } 

的那些对于iOS 9,一定要注册您的通知, didBecomeActive

UIApplication.shared.registerUserNotificationSettings(UIUserNotificationSettings(types: [.sound, .alert, .badge], categories: nil)) 
UIApplication.shared.registerForRemoteNotifications() 

,并在您didReceiveRemoteNotification

func application(_ application: UIApplication, didReceiveRemoteNotification data: [AnyHashable : Any]) { 

if application.applicationState == .active { 
//foreground state 
} 

} 

最好的办法是把一个调试器didReceiveRemoteNotification和进一步检查。

+0

请确保导入用户通知 检查此答案https://stackoverflow.com/q/38940193/2570153 –

+1

虽然我使用Objective-C,而不是Swift,但这是正确的答案。我忘了实现在前台调用的'UNUserNotificationCenterDelegate'方法,而不是'didReceiveRemoteNotification:fetchCompletionHandler:'iOS 10 –

+0

@mag_zbc太棒了! –