我尝试下载图像:
URLSession.shared.dataTask(with: URL(string: urlString)! as URL, completionHandler: { (data, response, error) -> Void in
...
}).resume()
此代码非常适合网址:
https://website.com/abo_beach.jpg
但是当我尝试下载瑞典语链接时:
https://website.com/åbo_beach.jpg
用字母"å",我得到这个错误:致命错误:解开可选值时意外发现 nil
如何从瑞典语链接下载图像?
Abdelahad Darwish的答案是一个改进,也许可以解决你的特定问题(非法字符(,但一般来说,你会希望检测这些类型的错误并优雅地失败,而不是冒着应用程序崩溃的风险。
特别是,不要!
返回可选值(即可能会失败(的方法,而是添加必要的检查:
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()