【问题标题】:WatchOS, SwiftUI: How to send local notifications with a 'View' as bodyWatchOS,SwiftUI:如何以“视图”为正文发送本地通知
【发布时间】:2020-05-22 12:06:03
【问题描述】:

在创建 XCode 项目时,我选择了 Apple Watch 应用程序并启用了“包含通知”。 这导致我的项目中有一个 NotificationView.swift 和一个 NotificationController.swift。

我已经在 NotificationView.swift 中填写了我希望在本地通知中显示的视图内容。

在我的常规 HostingController.swift 中,我现在想安排一个包含 NotificationView.swift 内容的本地通知。

到目前为止,我使用的是当前代码:

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

我没有对关于 categoryIdentifier 的 Info.plist 进行任何更改。 我现在必须在哪里添加代码才能“捕获”此通知并用我的自定义 NotificationView.swift 内容填充它?

【问题讨论】:

    标签: swiftui watchkit watchos usernotifications


    【解决方案1】:

    您是否请求用户允许发送通知?

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

    它只在第一次出现权限警报:一旦获得权限就不会再次出现。

    【讨论】:

      猜你喜欢
      • 2023-01-11
      • 2023-01-05
      • 1970-01-01
      • 2018-04-18
      • 2016-12-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多