watchOS Notifications - Part 2

Episode #257 | 16 minutes | published on February 24, 2017 | Uses watchOS-3, Xcode-8.2
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)
}
blog comments powered by Disqus