如何从userNotificationCenter读取内容-Swift

时间:2018-06-22 22:40:41

标签: swift xcode push-notification

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

1 个答案:

答案 0 :(得分: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类型的值?'到预期的参数类型'Data'“

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

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

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

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