2016-05-14 64 views
0

的USERINFO对象符合要求使用夫特-2.2,为UILocalNotification

我想传递一个“结构”或“类对象”到UILocalNotification的用户信息。 (请参阅下面的代码图)。

你能告诉我如何改变这个结构以符合UserInfo的要求吗?

我读一些有关

一)的UserInfo不能是一个结构(但我也试图与一类 - 它没有工作,要么)

二)“的plist型”整合 - >但我该怎么做?

c)“NSCoder”和“NSObject”符合 - >但我该怎么做?

该错误消息我得到运行下面的代码是:

“无法序列USERINFO”

感谢您有这方面的帮助。

struct MeetingData { 
    let title: String 
    let uuid: String 
    let startDate: NSDate 
    let endDate: NSDate 
} 

let notification = UILocalNotification() 
notification.category = "some_category" 
notification.alertLaunchImage = "Logo" 
notification.fireDate = NSDate(timeIntervalSinceNow: 10) 
notification.alertBody = "Data-Collection Request!" 
//  notification.alertAction = "I want to participate" 
notification.soundName = UILocalNotificationDefaultSoundName 

let myData = MeetingData(title: "myTitle", 
          uuid: "myUUID", 
        startDate: NSDate(), 
         endDate: NSDate(timeIntervalSinceNow: 10)) 

// that's where everything crashes !!!!!!!!!!!!!! 
notification.userInfo = ["myKey": myData] as [String: AnyObject] 

回答

1

由于文档UILocalNotification.userInfo说:

您可以添加任意的键值对本字典。但是,密钥和值必须有效property-list types;如果有的话,则会引发异常。

您需要自己将数据转换为此类型。你可能想要做这样的事情:

enum Keys { 
    static let title = "title" 
    static let uuid = "uuid" 
    static let startDate = "startDate" 
    static let endDate = "endDate" 
} 
extension MeetingData { 
    func dictionaryRepresentation() -> NSDictionary { 
     return [Keys.title: title, 
       Keys.uuid: uuid, 
       Keys.startDate: startDate, 
       Keys.endDate: endDate] 
    } 
    init?(dictionaryRepresentation dict: NSDictionary) { 
     if let title = dict[Keys.title] as? String, 
      let uuid = dict[Keys.uuid] as? String, 
      let startDate = dict[Keys.startDate] as? NSDate, 
      let endDate = dict[Keys.endDate] as? NSDate 
     { 
      self.init(title: title, uuid: uuid, startDate: startDate, endDate: endDate) 
     } else { 
      return nil 
     } 
    } 
} 

然后你可以使用myData.dictionaryRepresentation()转换为一个字典,并MeetingData(dictionaryRepresentation: ...)从字典转换。

+0

这是一个很好的解决方案 - 非常感谢你! – iKK