I want to use a cutom object in userinfo of a UNMutableNotificationContent but it doesn’t work. When I put a custom object in userinfo, notification is not fired.
With this code, a notification is fired:
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!)
}
}
With the following, no error but notification is not fired:
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 is the custom class, here is the definition:
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
}
}
}
Any idea?
You object should be Property List
you can convert your object to NSData (archive it using NSArchiver)