WatchOS, SwiftUI: How to send local notifications with a 'View' as body
Asked Answered
L

1

6

When creating the XCode project, I selected Apple Watch Application and enabled "Include Notification". This lead me to have a NotificationView.swift and a NotificationController.swift in my project.

I have filled the NotificationView.swift with the View content i would like to be in my local notification.

In my regular HostingController.swift I would now like to schedule a local notification with the content of NotificationView.swift.

So far, I am using the current code:

let userNotificationCenter = UNUserNotificationCenter.current()
let notificationContent = UNMutableNotificationContent()
notificationContent.title  = "title"
notificationContent.body = "body"
notificationContent.categoryIdentifier = "categoryNameDummy"

let category = UNNotificationCategory(identifier: "categoryNameDummy", actions: [], intentIdentifiers: [] as? [String] ?? [String](), options: .customDismissAction)
let categories = Set<AnyHashable>([category])

userNotificationCenter.setNotificationCategories(categories as? Set<UNNotificationCategory> ?? Set<UNNotificationCategory>())

let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 2, repeats: false)

let request = UNNotificationRequest(identifier: UUID().uuidString, content: notificationContent, trigger: trigger)
userNotificationCenter.add(request) { (error) in
if let error = error {
    debugPrint(error)
}
}

I have not made any changes to Info.plist regarding the categoryIdentifier. What and where do I have to add code to now "catch" this notification and fill it with my custom NotificationView.swift content?

Lozenge answered 6/2, 2020 at 12:28 Comment(0)
C
0

Did you ask the user for permission to send notifications?

    UNUserNotificationCenter.current().requestAuthorization(options: [.sound, .alert]) { success, error in
        if success {
            print("Ok!")
        } else if let error = error {
            print(error.localizedDescription)
        }
    }

It only presents a permission alert the first time: once given permission it won't show up again.

Cotidal answered 15/1, 2021 at 9:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.