Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UNMutableNotificationContent with custom object in userinfo

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?

like image 891
squall2022 Avatar asked Dec 28 '16 10:12

squall2022


1 Answers

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)

like image 131
Red Mak Avatar answered Oct 14 '22 21:10

Red Mak