Adding Action to Notifications on WatchOS with SwiftUI And WatchKit App Delegate

Set Up Local Notifications:

import SwiftUIimport UserNotificationsstruct ContentView: View {var body: some View {VStack{Button("Request permission"){UNUserNotificationCenter.current().requestAuthorization(options: [.alert,.sound,.badge]) { (success, error) inif success{print("All set")} else if let error = error {print(error.localizedDescription)}}}Button("Schedule Notification"){let content = UNMutableNotificationContent()content.title = "Drink some milk!"content.subtitle = "you have 10 sec"content.sound = .defaultcontent.categoryIdentifier = "myCategory"let doneAction = UNNotificationAction(identifier: "done", title: "Done", options: .foreground)let laterAction = UNNotificationAction(identifier: "later", title: "Later", options: .destructive)let category = UNNotificationCategory(identifier: "myCategory", actions: [doneAction,laterAction], intentIdentifiers: [], options: [])UNUserNotificationCenter.current().setNotificationCategories([category])let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)let request = UNNotificationRequest(identifier: "milk", content: content, trigger: trigger)UNUserNotificationCenter.current().add(request) { (error) inif let error = error{print(error.localizedDescription)}else{print("scheduled successfully")}}}}}}
  1. Open “ExtensionDelegate”.
  2. Import “UserNotifications” .
  3. Make ExtensionDelegate subclass of “UNUserNotificationCenterDelegate” .
  4. Add “didReceive response” function to ExtensionDelegate class.
  5. To make “didReceive response” work you should set the delegate for “UNUserNotificationCenter” Like below:
func applicationDidFinishLaunching() {// Perform any final initialization of your application.let center = UNUserNotificationCenter.current()center.delegate = self}



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store