11

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?

squall2022
  • 214
  • 4
  • 9
  • 3
    I have the same problem, for example i want to pass an UIImage in userInfo and not notification is not fired at all. It seems that you can pass only primitive types (Int, String, floats etc). – Alessio Dal Bianco Jan 09 '17 at 14:14

1 Answers1

8

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)

Red Mak
  • 1,176
  • 2
  • 25
  • 56