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 Source Code Notification Essentials App Programming Guide for watchOS UNNotifications API Reference 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]) }