cndv
cndv

Reputation: 497

NSUrl returns nil while unwrapping

NSUrl returns nil while running this code.

let urlString = "https://api.flickr.com/services/rest/?text=baby asian elephant&method=flickr.photos.search&format=json&nojsoncallback=1&extras=url_m&safe_search=2&api_key=ed8f0359ce87560e56cda1fe71e8ad9d"
let url = NSURL(string: urlString)!

Throws an:

EXC_BAD_INSTRUCtION

Any ideas why this is happening.

Thank you.

Upvotes: 1

Views: 265

Answers (4)

zaph
zaph

Reputation: 112875

The URL String has characters that need to be escaped: the space characters. Here is example code to escaped the URL:

let urlString = "https://api.flickr.com/services/rest/?text=baby asian elephant&method=flickr.photos.search&format=json&nojsoncallback=1&extras=url_m&safe_search=2&api_key=ed8f0359ce87560e56cda1fe71e8ad9d"

let escapedString = urlString.stringByAddingPercentEncodingWithAllowedCharacters(.URLQueryAllowedCharacterSet())

if  let escapedString = escapedString {
    let url = NSURL(string: escapedString)
    if let url = url {
        println("url: \(url)")
    }
}

Output

url: https://api.flickr.com/services/rest/?text=baby%20asian%20elephant&method=flickr.photos.search&format=json&nojsoncallback=1&extras=url_m&safe_search=2&api_key=ed8f0359ce87560e56cda1fe71e8ad9d

Upvotes: 1

luk2302
luk2302

Reputation: 57184

The problem are the whitespace in the urlString.

They need to be replaced. Whitespaces in URLs are written as %20 instead of :

let urlString = "https://api.flickr.com/services/rest/text=baby%20asian%20elephant&method=flickr.photos.search&format=json&nojsoncallback=1&extras=url_m&safe_search=2&api_key=ed8f0359ce87560e56cda1fe71e8ad9d"

I am guessing that you somehow insert the text parameter by yourself?! This parameter would need to be escaped first, Zaph has already pointed out the neccessary methods for that case.

Upvotes: 2

Peter Lendvay
Peter Lendvay

Reputation: 655

There shouldn't be whitespace in the URL.

Upvotes: 2

Superolo
Superolo

Reputation: 98

You can't have white spaces in the urlString

let urlString = "https://api.flickr.com/services/rest/?text=baby%20asian%20elephant&method=flickr.photos.search&format=json&nojsoncallback=1&extras=url_m&safe_search=2&api_key=ed8f0359ce87560e56cda1fe71e8ad9d"
let url = NSURL(string: urlString)!

Upvotes: 1

Related Questions