Reputation: 497
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
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
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
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