gpt4 book ai didi

swift - UILocalNotification 的 userInfo 对象的符合性要求

转载 作者:行者123 更新时间:2023-11-30 10:03:35 25 4
gpt4 key购买 nike

使用 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]

最佳答案

正如 UILocalNotification.userInfo 的文档所述:

You may add arbitrary key-value pairs to this dictionary. However, the keys and values must be valid property-list types; if any are not, an exception is raised.

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

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: ...) 从字典转换。

关于swift - UILocalNotification 的 userInfo 对象的符合性要求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37229919/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com