【问题标题】:UNMutableNotificationContent with custom object in userinfo用户信息中带有自定义对象的 UNMutableNotificationContent
【发布时间】:2017-05-12 15:31:56
【问题描述】:

我想在 UNMutableNotificationContent 的用户信息中使用自定义对象,但它不起作用。 当我将自定义对象放入 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!)
    }
}

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

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

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

}

有什么想法吗?

【问题讨论】:

  • 我有同样的问题,例如我想在 userInfo 中传递一个 UIImage 并且根本不会触发通知。似乎您只能传递原始类型(Int、String、float 等)。

标签: ios swift notifications userinfo nssecurecoding


【解决方案1】:

你的对象应该是属性列表

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

您可以将您的对象转换为 NSData(使用 NSArchiver 存档)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-05-19
    • 2013-08-19
    • 1970-01-01
    • 2012-12-25
    • 2016-09-16
    • 1970-01-01
    • 1970-01-01
    • 2014-03-05
    相关资源
    最近更新 更多