【问题标题】:How to read the content from userNotificationCenter - Swift如何从 userNotificationCenter 读取内容 - Swift
【发布时间】:2018-06-22 22:40:41
【问题描述】:

如何读取“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":""})

【问题讨论】:

  • 这是一个 JSON String - 很多关于在 Swift 中读取 JSON 的示例,包括 CodableSwiftyJSON
  • 我尝试使用 swifty json 但它不起作用。
  • 我无法处理此消息:“无法转换 'Any?' 类型的值?到预期的参数类型“数据”“
  • if let magazin = userInfo["magazin"] as? String { ... }

标签: swift xcode push-notification


【解决方案1】:

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

所以,我把你的数据,扔到操场上并使用......

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

我无法处理此消息:“无法转换 'Any?' 类型的值?”到预期的参数类型“数据”“

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

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

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

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

【讨论】:

    猜你喜欢
    • 2016-05-21
    • 1970-01-01
    • 1970-01-01
    • 2017-04-18
    • 1970-01-01
    • 2016-11-02
    • 2018-06-09
    • 2010-11-02
    • 2020-03-19
    相关资源
    最近更新 更多