4
UNMutableNotificationContentのuserinfoでcutomオブジェクトを使用したいが、動作しません。 userinfoにカスタムオブジェクトを配置すると、通知は発生しません。このコード、通知が発射されると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
}
}
}
私は同じ問題を抱えてたNSDataにあなたのオブジェクトに変換することができ、例えば、私はのUserInfoにUIImageを渡したいとしませ通知は一切発生しません。あなたはプリミティブ型(Int、String、floatなど)だけを渡すことができるようです。 – USSliberty