Episode #256

watchOS Notifications - Part 1

Series: Up to Speed with watchOS

16 minutes
Published on February 16, 2017

This video is only available to subscribers. Get access to this video and 534 others.

In this episode Dory Glauberman covers how to set up notifications in your application on both the iPhone and Apple Watch using UNUserNotificationCenter. It highlights best practices for requesting notification authorization and demonstrates how to fire a sample notification for the Beer Button watch app.

This week's guest author is Dory Glauberman. Dory works for Mutual Mobile in Austin, TX. You can find Dory on Twitter.

Episode Links

Requesting Authorization for Notifications

let center = UNUserNotificationCenter.current()
center.requestAuthorization(options: [.alert, .sound]) { (granted, error) in
    if granted {
        let category = UNNotificationCategory(identifier: "BeerButtonOrderDelivery", actions: [], intentIdentifiers: [], options: [])
        center.setNotificationCategories(Set([category]))
    } else {
        print("No permission" + error.debugDescription)
    }
}

Determining Authorization Status Without Prompting User

let center = UNUserNotificationCenter.current()
center.delegate = self
center.getNotificationSettings { (settings) in
    if settings.authorizationStatus == .notDetermined {
        // user has not seen apple notification authorization prompt
    }
}

Handle Notifications Received While App is in Foreground

func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    // this shows the notification, alternatively you could change app state based on the notification or ignore the notification
    completionHandler([.alert, .sound])
}

This episode uses Watchos 3, Xcode 8.2.