声明本地通知的标题、副标题和 body

Declaring the title, subtitle, and body of a local notification

func scheduleNotification(inSeconds: TimeInterval, completion: @escaping (_ Success: Bool) -> ()) {

        let notif = UNNotificationContent()

         notif.title = NSString.localizedUserNotificationString(forKey: "New Notification", arguments: nil)
        notif.subtitle = "These are great!"
        notif.body = "The new notification options are awesome!"

        let notifTrigger = UNTimeIntervalNotificationTrigger(timeInterval: inSeconds, repeats: false)

        let request = UNNotificationRequest(identifier: "myNotification", content: notif, trigger: notifTrigger)

        UNUserNotificationCenter.current().add(request, withCompletionHandler: {error in
            if error != nil {
                print(error)
                completion(false)
            } else {
                completion(true)
            }

        })
    }

我正在观看 Udemy 视频,但在设置本地通知的标题、副标题和 body 时遇到问题。我对所有三个分配行都得到了相同的错误。

Cannot assign to property: 'xxx' is a get-only property.

我很快在文档中查找了它。它说:

Do not create instances of this class directly. (...) For local notifications, create a UNMutableNotificationContent object and configure the contents of that object instead.

来源:https://developer.apple.com/documentation/usernotifications/unnotificationcontent

我不太熟悉这个 class 但我认为 UNNotificationContent 会根据接收到的数据自动填充内容。

我不确定这是否是您要查找的内容,但也许可以尝试使用 UNMutableNotificationContent 而不是 UNNotificationContent:

let notif = UNMutableNotificationContent()