Search code examples
iosswiftpush-notificationapple-push-notificationswatchkit

WatchKit 2.0 Detect When APNS Is Received


I am creating an Apple Watch application which has a chat feature. I would like to update the chat conversation whenever the watch app is running and an APNS message is received. I know in the AppDelegate, the function

application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) 

can be used, but that's only when the device application is running in the foreground, not background. In the WKUserNotificationInterfaceController, there is the function didReceiveRemoteNotification, but that is only used when using a Dynamic Notification. Is it possible to have the watch application process a remote notification that is received when not using Dynamic Notifications and is running in the foreground?


Solution

  • When creating a WatchKit app, and using APNS, there's few things you need to know about how a push notification actually work on the Watch side.

    1) It's the iOS system which choose wether or not the notification is handled by Watch, based on user activity (iPhone locked/unlocked; Watch is used/not used...).

    When one of your app’s local or remote notifications arrives on the user’s iPhone, iOS decides whether to display that notification on the iPhone or on the Apple Watch. See Doc Apple

    2) For the iOS side you can handle all your notifications in didReceiveRemoteNotificationapplication(_:didReceiveRemoteNotification:fetchCompletionHandler:) ==> you can check wether or not your app is in foreground + handle silent notifications.

    3) There is two distinct entry points for notifications on the Watch side:

    • As you said, there's theWKUserNotificationInterfaceController which is called when your WatchKit app is not used.
    • And there's didReceiveRemoteNotification(_:) in your ExtensionDelegate class, which is called when your WatchKit app is running. See here for complete documentation.

    If you need to update your app while it's running, through APNS, you should handle it in this last method ;)

    Hope it'll help you!