代码之家  ›  专栏  ›  技术社区  ›  iKK

UILocalNotification的userInfo对象的符合性要求

  •  0
  • iKK  · 技术社区  · 10 年前

    使用Swift-2.2,

    我想将“struct”或“class object”传递给UILocalNotification的userInfo。(参见下面的代码说明)。

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

    我读了一些关于

    a) UserInfo不能是一个结构(但我也尝试了一个类,它也不起作用)

    b) “plist type”一致性-->但我该怎么做呢?

    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 回复  |  直到 10 年前
        1
  •  1
  •   jtbandes    10 年前

    作为以下文件 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: ...) 从字典中转换。