简体   繁体   中英

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.

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.

URL中不应包含空格。

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)!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM