ffritz
ffritz

Reputation: 2261

Convert JSON from Notification into URL

I am having a bit of trouble with converting a body message I am receiving from a notification into a URL. I am getting the following error:

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

I am doing this the following way:

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

The JSON Structure is aps: { alert: { body: "www.google.com"

Question: Why is the casting failing here?

Upvotes: 0

Views: 97

Answers (1)

rmaddy
rmaddy

Reputation: 318824

A String is not a URL. You need to create a URL from a String using the proper URL initializer, not by trying to cast it.

You should also write more defensive code by safely unwrapping.

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
            }
        }
    }
}

You could also shorten this to:

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
    }
}

Upvotes: 2

Related Questions