Search code examples
iosswiftnotificationswatchkitwatchos

Background Notifications on WatchOS 3 (XCode 8b6)


I have foreground notifications on watch working with:

class WorkoutInterfaceController:   WKInterfaceController,
                                    UNUserNotificationCenterDelegate

set delegate:

UNUserNotificationCenter.current().delegate = self

receive foreground notification:

func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Swift.Void)
{
    print("Received Notification .....")
    UNUserNotificationCenter.current().removeAllDeliveredNotifications()
    let completionSound: UNNotificationPresentationOptions = [.sound, .alert]
    completionHandler(completionSound)
}

add a notification:

    let content: UNMutableNotificationContent = UNMutableNotificationContent()

    content.title = "TITLE"
    content.subtitle = "sub title"
    content.body = "message body"
    content.sound = UNNotificationSound.default()

    let trigger = UNTimeIntervalNotificationTrigger(timeInterval: duration, repeats: false)

    let request = UNNotificationRequest(identifier: restOverIdentifier,
                                        content: content,
                                        trigger: trigger)

    UNUserNotificationCenter.current().add(request)
    {
        (error) in // ...
    }

I have tried on both the sim and device with no luck getting a notification when the sim is locked or on home screen or on watch when the screen goes black if you don't move your arm.

All I am looking for is a simple beep I don't even need the notification alert screen.

Please post code if you have something working for this or confirm this function is not working on watch.

Thanks

Greg


Solution

  • There is a bug with watchOS 3 where only the first notification is displayed:

    Changing my code temporarily to:

        let id: String = WatchNotify.getUUID()
    
        //        let request = UNNotificationRequest(identifier: focusWarningIdentifier,
        let request = UNNotificationRequest.init(identifier: id,
                                            content: content,
                                            trigger: trigger)
    
        UNUserNotificationCenter.current().add(request)
    

    with this added function for a UUID:

    class func getUUID() -> String
    {
        let uuidObj = CFUUIDCreate(nil)
        let uuidString = CFUUIDCreateString(nil, uuidObj)!
        return uuidString as String
    }
    

    Seems to do the trick although the delegate completion handler does not appear to work on the watch yet.