Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

swift - 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

UPDATE #1 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 background.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...