import Combine import SwiftUI import UserNotifications import WatchConnectivity @main struct APP: App { #if os(iOS) @UIApplicationDelegateAdaptor(AppDelegate.self) var delegate #elseif os(watchOS) @WKApplicationDelegateAdaptor(AppDelegate.self) var delegate #endif var body: some Scene { WindowGroup { ContentView() } } } struct ContentView: View { @EnvironmentObject var appDelegate: AppDelegate var body: some View { Button("Notify") { Task { let id = UUID().uuidString await self.appDelegate.callNotification(id: id) WCSession.default.sendMessage(["id" : id], replyHandler: nil) } } } } @MainActor class AppDelegate: NSObject, ObservableObject, @preconcurrency UNUserNotificationCenterDelegate, @preconcurrency WCSessionDelegate { func callNotification(id: String) async { try! await UNUserNotificationCenter.current() .add( .init( identifier: id, content: { let value = UNMutableNotificationContent() #if os(iOS) value.title += "Hello for iOS" #elseif os(watchOS) value.title += "Hello for watchOS" #endif value.body = "id: " + id value.sound = .default return value }(), trigger: UNTimeIntervalNotificationTrigger(timeInterval: 0.1, repeats: false) ) ) } func session(_ session: WCSession, didReceiveMessage message: [String : Any]) { Task { @MainActor in await self.callNotification(id: message["id"]! as! String) } } func userNotificationCenter( _ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void ) { completionHandler([.banner, .list, .sound]) } override init() { super.init() let wcSession = WCSession.default wcSession.delegate = self wcSession.activate() let userNotificationCenter = UNUserNotificationCenter.current() userNotificationCenter.delegate = self Task { try! await userNotificationCenter.requestAuthorization(options: [.alert, .badge, .sound]) } } func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: (any Error)?) {} #if os(iOS) func sessionDidBecomeInactive(_ session: WCSession) {} func sessionDidDeactivate(_ session: WCSession) {} #endif } #if os(iOS) extension AppDelegate: UIApplicationDelegate {} #elseif os(watchOS) extension AppDelegate: WKApplicationDelegate {} #endif