【问题标题】:conformity requirements for userInfo object of UILocalNotificationUILocalNotification 的 userInfo 对象的一致性要求
【发布时间】:2016-05-14 17:42:59
【问题描述】:

使用 Swift-2.2,

我想将“结构”或“类对象”传递给 UILocalNotification 的 userInfo。 (参见下面的代码说明)。

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

我读到了一些关于

a) UserInfo 不能是结构(但我也尝试过使用类 - 它也不起作用)

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

c) "NSCoder" 和 "NSObject" 一致性 --> 但我该怎么做呢?

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

“无法序列化用户信息”

感谢您对此提供的任何帮助。

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]

【问题讨论】:

    标签: swift uilocalnotification userinfo


    【解决方案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: ...)从字典转换。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-08
      • 1970-01-01
      • 1970-01-01
      • 2019-03-26
      相关资源
      最近更新 更多