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

Hamidreza Farzi
2 min readFeb 6, 2021

--

In previous article, we find out how to show a dynamic notification, In this article we want to add response to our local notifications.

Set Up Local Notifications:

First of all, we should set local notifications, I use my previous project, where we want to set notification category we should add actions to notification:

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")}}}}}}

Perfect! now we can see our actions right below the notification view:

but now when users tap on actions, app opens automatically, how we can find out which action user tapped? To find out:

  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}

finished! now we can find out the action that user has been selected.

--

--