[英]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.