UNMutableNotificationContent with custom object in userinfo

5.6k views Asked by At

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?

1

There are 1 answers

0
Red Mak On

You object should be Property List

The keys in this dictionary must be property-list types—that is, they must be types that can be serialized into the property-list format. For information about property-list types, see Property List Programming Guide.

you can convert your object to NSData (archive it using NSArchiver)