SwiftUI on watchOS - Notifications

These are notes I’ve taken while watching the video of the corresponding session. They don’t have all the information contained in the video, but I’ve tried to still write the main points for my personal use cases.

Tick on the box to include notifications on a new project.

Notice thattheclass is a subclass of WKUserNotificationHostingController

Implement the didReceive method to customize your view. You can for example add notificationActions

import SwiftUI
import UserNotifications
class NotificationController:WKUserNotificationHostingController<NotificationView>{
  var mealResponse:MealResponse!
  override var body: NotificationView{
     NotificationView(mealResponse:mealResponse)
  }
    override func didReceive(\_ notification: UINotification){
      let mealResponseInfo = notification.request.content.userInfo['meal'] ?? [:] as! [String:String]
     mealResponse = mealResponse(text: "Your meal arrived")

      notificationActions = [
      UINotificationAction(identifier: "ok", title:"Ok",options:[])
      ]
  }
}

NotificationView is a normal SwiftUI view.

Image

Valentino Urbano

iOS Developer, Swift, Writer, Husband

Back to Overview