简体   繁体   中英

URLSession.shared.dataTask can't download image with swedish url

I try to download image:

URLSession.shared.dataTask(with: URL(string: urlString)! as URL, completionHandler: { (data, response, error) -> Void in

            ...

        }).resume()

This code works perfectly for url:

https://website.com/abo_beach.jpg

But when I try to download Swedish link:

https://website.com/åbo_beach.jpg

with letter "å", I got this error: fatal error: unexpectedly found nil while unwrapping an Optional value

How can I download image from Swedish link ?

The answer by Abdelahad Darwish is an improvement and perhaps fixes your particular problem (illegal characters), but in general you would want to detect these kind of errors and fail gracefully instead of risk crashing your app.

In particular, stay away from ! on methods that return an optional value (ie, can potentially fail) and add the necessary checks instead:

var urlString: String = "https://website.com/åbo_beach.jpg".stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())!

guard let url = URL(string: urlString) else {
    // String can not yield a valid URL; do someting!
    return
}

URLSession.shared.dataTask(with: url, completionHandler: { (data, response, error) -> Void in
        // ...
}).resume()

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