gpt4 book ai didi

swift - 如何从 userNotificationCenter 中读取内容 - Swift

转载 作者:行者123 更新时间:2023-11-28 11:55:56 25 4
gpt4 key购买 nike

如何读取“magazin”的值?

func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
let action = response.actionIdentifier
let request = response.notification.request
let userInfo = request.content.userInfo

if action == "open.magazin" {
var str: String?
let magazin = userInfo["magazin"]
print("MAGAZYN : \(magazin)")

}
completionHandler()
}

函数返回值:

MAGAZYN : Optional({"pages":100,"size":"50 MB","productId":"com.sad","purchased":false,"coverImageURL":"","cat":3,"itemPrice":"4,99","fileURL":"","id":5,"title":"test","demoStartPage":0,"desc":""})

最佳答案

Swift 4 提供了非常强大的开箱即用的 JSON 解析。我最喜欢的博客是 Ultimate Guide to JSON Parsing with Swift 4 ,因为我做的不够频繁,而且它以一种简单的方式涵盖了许多“陷阱”。

所以,我拿了你的数据,把它扔到 Playground 上,然后用...

let userInfo: [AnyHashable: Any] = ["magazin": "{\"pages\":100,\"size\":\"50 MB\",\"productId\":\"com.sad\",\"purchased\":false,\"coverImageURL\":\"\",\"cat\":3,\"itemPrice\":\"4,99\",\"fileURL\":\"\",\"id\":5,\"title\":\"test\",\"demoStartPage\":0,\"desc\":\"\"}"]

struct Magazin: Codable {
let pages: Int
let size: String
let productId: String
let purchased: Bool
let coverImageURL: String
let cat: Int
let itemPrice: String
let fileURL: String
let id: Int
let title: String
let demoStartPage: Int
let desc: String
}

if let magazin = userInfo["magazin"] as? String {
let jsonData = magazin.data(using: .utf8)!
let decoder = JSONDecoder()
let mag = try! decoder.decode(Magazin.self, from: jsonData)
print(mag.pages)
print(mag.size)
print(mag.productId)
print(mag.purchased)
print(mag.coverImageURL)
print(mag.cat)
print(mag.itemPrice)
print(mag.fileURL)
print(mag.id)
print(mag.title)
print(mag.demoStartPage)
print(mag.desc)
}

即将输出

100
50 MB
com.sad
false

3
4,99

5
test
0

注意 我在上面的例子中使用了强制解包,我希望你清理它并适当使用 guarddo-catch

I can not cope with this message: "Can not convert value of type 'Any?' to expected argument type 'Data' "

所以,有两件事,userInfo 是一个 [AnyHasable: Any] 风格的字典,所以您需要做的第一件事就是将值转换为合适的类型,根据您的示例,这可能是一个 String...

if let magazin = userInfo["magazin"] as? String {
//...
}

接下来,您需要将String 转换为Data

if let jsonData = magazin.data(using: .utf8) {
//...
}

关于swift - 如何从 userNotificationCenter 中读取内容 - Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50996376/

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