2017-01-04 1 views
1

Я пытаюсь реализовать UNUserNotification в своем приложении. В целом это работает, но мне нужно, чтобы передать свой объект с USERINFO (а затем получить его):UNMutableNotificationContent с пользовательским объектом в userInfo crashes app

static func showNotification(_ serverNotification: ServerNotification){ 
    print("showNotification called") 
    let content = UNMutableNotificationContent() 
    content.title = serverNotification.title 
    content.body = serverNotification.notificationDescription 
    content.sound = UNNotificationSound.default() 
    content.categoryIdentifier = "pl.tropicalapps.TryOnNotification" 
    content.userInfo = ["serverNotification" : serverNotification] 
    let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 1, repeats: false) 
    let request = UNNotificationRequest(identifier: "Request", content: content, trigger: trigger) 
    let center = UNUserNotificationCenter.current() 
    center.add(request) { (error:Error?) in 
     if let err = error { 
      print(err) 
     } 
     else{ 
      print("notification sent!") 
     } 
    } 
} 

Если я не буду добавлять USERINFO или передать [ «Foo»: «бар»] это работает. Но когда я добавляю свой объект (serverNotification), он сбрасывается после отправки запроса. Я не могу уловить эту ошибку, но она находится в `- [NSXPCEncoder _checkObject:]: (остаток находится в ассемблере).

Вот ServerNotification класс:

class ServerNotification : NSCoder { 

    var id:Int 
    var type:String 
    var brandId:Int 
    var title:String 
    var notificationDescription:String = "" 
    var discountId:String 
    var discountPercent:Double 
    var discountDescription:String 
    var discountCode:String 
    var discountType:String 
    var discountExpireDate:Date 
    var date:Date 

    override init(){ 
     id = 0 
     type = "" 
     brandId = 0 
     title = "" 
     notificationDescription = "" 
     discountId = "" 
     discountPercent = 0.0 
     discountDescription = "" 
     discountCode = "" 
     discountType = "" 
     discountExpireDate = Date() 
     date = Date() 
    } 

    required init(coder aDecoder: NSCoder) { 
     id = aDecoder.decodeInteger(forKey: "id") 
     type = aDecoder.decodeObject(forKey: "type") as! String 
     brandId = aDecoder.decodeInteger(forKey: "brandId") 
     title = aDecoder.decodeObject(forKey: "title") as! String 
     notificationDescription = aDecoder.decodeObject(forKey: "notificationDescription") as! String 
     discountId = aDecoder.decodeObject(forKey: "discountId") as! String 
     discountPercent = aDecoder.decodeDouble(forKey: "discountPercent") 
     discountDescription = aDecoder.decodeObject(forKey: "discountDescription") as! String 
     discountCode = aDecoder.decodeObject(forKey: "discountCode") as! String 
     discountType = aDecoder.decodeObject(forKey: "discountType") as! String 
     discountExpireDate = aDecoder.decodeObject(forKey: "discountExpireDate") as! Date 
     date = aDecoder.decodeObject(forKey: "date") as! Date 
     super.init() 
    } 

    func encodeWithCoder(_ aCoder: NSCoder){ 
     aCoder.encode(id, forKey: "id") 
     aCoder.encode(type, forKey: "type") 
     aCoder.encode(brandId, forKey: "brandId") 
     aCoder.encode(title, forKey: "title") 
     aCoder.encode(notificationDescription, forKey: "notificationDescription") 
     aCoder.encode(discountId, forKey: "discountId") 
     aCoder.encode(discountPercent, forKey: "discountPercent") 
     aCoder.encode(discountDescription, forKey: "discountDescription") 
     aCoder.encode(discountCode, forKey: "discountCode") 
     aCoder.encode(discountType, forKey: "discountType") 
     aCoder.encode(discountExpireDate, forKey: "discountExpireDate") 
     aCoder.encode(date, forKey: "date") 
    } 
} 

Где проблема? Как я могу это исправить? Я бегу приложение на устройстве с прошивкой 10,2

ответ

1

Насколько я тестировал код с симулятором, немного последовал -[NSXPCEncoder _checkObject:]:

This coder only encodes objects that adopt NSSecureCoding (object is of class 'TestProjectName.ServerNotification').

Вы можете необходимо сделать заголовок вашего ServerNotification как:

class ServerNotification : NSObject, NSSecureCoding { 

Xcode покажет некоторые предложения с правом «Fix-it» s.

Обычно вы используете подкласс NSCoder, если вы хотите создать свой собственный архиватор/unarchiver, кроме этого, такое подклассы бесполезно.

+0

Ну, я использую свой архиватор/unarchiver. – Makalele

+0

@Makalele, архиватор/unarchiver должен отличаться от архивного объекта. Класс архивных объектов должен соответствовать «NSCoding» (** не ** 'NSCoder') или' NSSecureCoding', архиватор/unarchiver наследует 'NSCoder'. Вы действительно хотите создать замену для NSKeyedArchiver/'NSKeyedUnarchiver'? – OOPer