[英]performSegueWithIdentifier while in URLSession.shared.dataTask(with: url)
[英]URLSession.shared.dataTask can't download image with swedish url
我尝试下载图片:
URLSession.shared.dataTask(with: URL(string: urlString)! as URL, completionHandler: { (data, response, error) -> Void in
...
}).resume()
这段代码非常适合url:
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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.