Mr. A
Mr. A

Reputation: 714

How to receive local notification in watchOS 2

As I can read in guideline notifications are displayed automatically. But.. not for me. The question is why? My iOS app send notification after 4 seconds when user tap the button:

@IBAction func stopTimerPress(sender: AnyObject) {
        print("Stop timer!")
        notification.alertBody = "STOP!"
        self.timer = NSTimer.scheduledTimerWithTimeInterval(4.0, target: self, selector: "fire", userInfo: nil, repeats: true)
}

and then I expect that (if the app in iOS is in background) my Apple Watch display static notification. But it did not happen. What can I do? I uncommented this:

override func didReceiveLocalNotification(localNotification: UILocalNotification, withCompletion completionHandler: ((WKUserNotificationInterfaceType) -> Void)) {
        print(localNotification.alertBody)
        completionHandler(.Default)
    }

in NotificationController but this still didn't work. Can someone help me?

Upvotes: 2

Views: 962

Answers (2)

lehn0058
lehn0058

Reputation: 20257

Have you requested permission from the user to view notifications on the iOS app? If the iPhone screen is off (not just the app in the background) then it should forward the notification to the Apple Watch.

UIUserNotificationType types = UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert;
UIUserNotificationSettings *mySettings = [UIUserNotificationSettings settingsForTypes:types categories:nil];
[[UIApplication sharedApplication] registerUserNotificationSettings:mySettings];

Also, if the Apple Watch app is in the foreground and the screen is on when the notification arrives, then it won't display in the UI, but instead will call the didReceiveLocalNotification method. If the screen is off, then this method won't get called but the notification will appear as a usual notification.

Upvotes: 1

Owen Hartnett
Owen Hartnett

Reputation: 5935

When you're in the background, your code is not running. However, If you click on your project in Xcode, and go to "Capabilities" and then into "Background Modes" and click "Remote Notifications." Then your app will be awakened at times known only to Apple, and then your code will be run provided it lasts no more than 30 seconds. You can use the Xcode menu item "Simulate Background Fetch" in the Debug menu to send a fetch message when your app is being debugged, to test.

Note that this may or may not run your code in 4 seconds - as Apple decides when to wake up your background app. I've seen it wake up every 5 minutes, or even after a couple of hours.

Upvotes: 0

Related Questions