2016-12-28 31 views
4

我想在UNMutableNotificationContent的userinfo中使用cutom對象,但它不起作用。 當我在用戶信息中放置一個自定義對象時,通知不會被觸發。UNMutableNotificationContent與用戶信息中的自定義對象

有了這個代碼,通知被解僱:

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 
     } 
    } 

} 

任何想法?

+2

我有同樣的問題,比如我想通過在用戶信息的UIImage的,而不是通知沒有解僱的。看起來你只能傳遞基本類型(Int,String,Float等)。 – USSliberty

回答

1

你的對象應該是屬性列表

在這個字典中的密鑰必須屬性列表類型,也就是說,他們 必須是可序列化到屬性列表格式類型。 有關屬性列表類型的信息,請參閱屬性列表 編程指南。

您可以將對象轉換爲NSData的(使用NSArchiver存檔)

相關問題