Episode #257

watchOS Notifications - Part 2

Series: Up to Speed with watchOS

16 minutes
Published on February 24, 2017

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

In this episode, Dory finishes up implementing notifications for the Beer Button watch app. We learn how to configure and send timed notifications, and how to respond to those on the watch.

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

Episode Links

Configure A UNNotificationRequest

let content = UNMutableNotificationContent()
content.title = "Beer Delivery"
content.body = "Your beer will be delivered in"
content.userInfo = message
content.sound = UNNotificationSound.default()
content.categoryIdentifier = "BeerButtonOrderDelivery"

let time = orderInfo.date.timeIntervalSinceNow - 20.0
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: time, repeats: false)
let request = UNNotificationRequest(identifier: stringWithUUID(), content: content, trigger: trigger)

Send a Notification

let center = UNUserNotificationCenter.current()

// optionally clear out pending and delivered notifications before adding new request
center.removeAllPendingNotificationRequests()
center.removeAllDeliveredNotifications()

center.add(request)

WKUserNotificationInterfaceController Default Handler

override func didReceive(_ notification: UNNotification, withCompletion completionHandler: @escaping (WKUserNotificationInterfaceType) -> Swift.Void) {
    completionHandler(.default)
}

WKUserNotificationInterfaceController Custom Handler

override func didReceive(_ notification: UNNotification, withCompletion completionHandler: @escaping (WKUserNotificationInterfaceType) -> Swift.Void) {
    // pull user info from notification request's content
    let request = notification.request
    let content = request.content
    let userInfo = content.userInfo

    // configure notification ui
    ...

    completionHandler(.custom)
}

This episode uses Watchos 3, Xcode 8.2.