将 JSON 从 Notification 转换为 URL

Convert JSON from Notification into URL

我在将收到的通知正文消息转换为 URL 时遇到了一些麻烦。我收到以下错误:

Could not cast value of type '__NSCFString' (...) to 'NSURL' (...)

我正在按以下方式执行此操作:

let aps = userInfo["aps"] as? Dictionary<String, AnyObject>
let alert = aps?["alert"] as? Dictionary<String, AnyObject>
let body = alert?["body"]
let url = body as! URL

JSON结构是aps: { alert: { body: "www.google.com"

问题:为什么这里转换失败?

A String 不是 URL。您需要使用正确的 URL 初始化程序从 String 创建一个 URL,而不是尝试强制转换它。

您还应该通过安全解包来编写更多防御性代码。

if let aps = userInfo["aps"] as? [String : AnyObject] {
    if let alert = aps["alert"] as? [String : AnyObject] {
        if let body = alert["body"] as? String {
            if let url = URL(string: body) {
                // do something with url
            }
        }
    }
}

您也可以将其缩短为:

if let aps = userInfo["aps"] as? [String : AnyObject], let alert = aps["alert"] as? [String : AnyObject], let body = alert["body"] as? String {
    if let url = URL(string: body) {
        // do something with url
    }
}