UNMutableNotificationContent与userinfo中的自定义对象

squ*_*022 11 notifications userinfo ios nssecurecoding swift

我想在UNMutableNotificationContent的userinfo中使用cutom对象,但它不起作用.当我在userinfo中放置自定义对象时,不会触发通知.

使用此代码,会触发通知:

let content = UNMutableNotificationContent()
content.title = "title"
content.body = "body"
content.categoryIdentifier = "alarmNotificationCategory"
content.sound = UNNotificationSound.default()
content.userInfo = ["myKey": "myValue"] as [String : Any]


let request = UNNotificationRequest(identifier: "alarmNotification", content: content, trigger: nil)
UNUserNotificationCenter.current().add(request) { error in
    UNUserNotificationCenter.current().delegate = self
    if error != nil {
        print(error!)
    }
}
Run Code Online (Sandbox Code Playgroud)

使用以下内容,不会发出错误,但不会触发通知:

let content = UNMutableNotificationContent()
content.title = "title"
content.body = "body"
content.categoryIdentifier = "alarmNotificationCategory"
content.sound = UNNotificationSound.default()
content.userInfo = ["myKey": TestClass(progress: 2)] as [String : Any]


let request = UNNotificationRequest(identifier: "alarmNotification", content: content, trigger: nil)
UNUserNotificationCenter.current().add(request) { error in
    UNUserNotificationCenter.current().delegate = self
    if error != nil {
        print(error!)
    }
}
Run Code Online (Sandbox Code Playgroud)

TestClass是自定义类,这里是定义:

class TestClass: NSObject, NSSecureCoding {
    public var progress: Float = 0

    required override public init() {
        super.init()
    }

    public init(progress: Float) {
        self.progress = progress
    }

    public required convenience init?(coder aDecoder: NSCoder) {
        self.init()
        progress = aDecoder.decodeObject(forKey: "progress") as! Float
    }

    public func encode(with aCoder: NSCoder) {
        aCoder.encode(progress, forKey: "progress")
    }

    public static var supportsSecureCoding: Bool {
        get {
            return true
        }
    }

}
Run Code Online (Sandbox Code Playgroud)

任何的想法?

Red*_*Mak 8

您的对象应该是属性列表

此字典中的键必须是属性列表类型 - 也就是说,它们必须是可以序列化为属性列表格式的类型.有关属性列表类型的信息,请参见"属性列表编程指南".

你可以将你的对象转换为NSData(使用NSArchiver归档它)