user1019042 user1019042 - 2 years ago 276
Swift Question

didReceiveRemoteNotification is not running when app is running (FOREGROUND)

I have a strange case. My swift ios app is connected to Cloudkit. If the app is NOT running (background state), I receive my notifications badge and alert just fine, every time!
If the app is running, no notifications are received! I know it is not hitting the remote because I do this:
1. Adding a breakpoint to the didReceiveRemoteNotification event
2. Running xcode in a plugged iphone
3. NSLog("detected didReceiveRemoteNotification"), so final code look like this

func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]){
NSLog("detected didReceiveRemoteNotification")

I know the error is not coming from cloudkit or from APNS because I do receive alert banner and badge when the phone is in the background state.

Can you guide me to set this up properly for the Foreground state!?

I am running ios v9.3

I think the wording of the documentation is poor. It clearly says that both run on the foreground, which is what I cared about; nevertheless, the fix is more accurate than the documentation!

Unlike the application:didReceiveRemoteNotification: method, which is
called only when your app is running in the foreground, the system
calls this method when your app is running in the foreground or

Answer Source

You've implemented the wrong method. Implement:

func application(_ application: UIApplication,
    didReceiveRemoteNotification userInfo: [NSObject : AnyObject],
    fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void)

As the docs explain:

Unlike the application:didReceiveRemoteNotification: method, ... the system calls this method when your app is running in the foreground or background.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download