我想从这个URL下载一张图片。
使用URL会话。
guard let newURL = url.addingPercentEncoding(withAllowedCharacters:NSCharacterSet.urlQueryAllowed), let url = URL(string: newURL), UIApplication.shared.canOpenURL(url) else {
// Failed
return
}
let config = URLSessionConfiguration.default
config.timeoutIntervalForResource = 30
config.timeoutIntervalForRequest = 30
let session = URLSession(configuration: config, delegate: self, delegateQueue: nil)
session.downloadTask(with: url).resume()
我在委托人中得到了回调,并且 状态码为404.
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
if let response = downloadTask.response as? HTTPURLResponse, response.statusCode == 404 {
return
}
if let data = try? Data(contentsOf: location), let image = UIImage(data: data) {
} else {
}
}
我在这里做错了什么?
一般来说,当你有一个url字符串。addingPercentEncoding
破坏了网址。
你没有显示原来的内容 url
(String)很清楚,但这段代码却能如愿以偿。
let urlString = "https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcSCLjkOCer-xuhkZuvvk3LJYiem4YkAJ869lUXSei5OtZ-SDLWi&usqp=CAU"
guard let url = URL(string: urlString) else {
print("Bad url string: \(urlString)")
return
}
let config = URLSessionConfiguration.default
config.timeoutIntervalForResource = 30
config.timeoutIntervalForRequest = 30
let session = URLSession(configuration: config, delegate: self, delegateQueue: nil)
session.downloadTask(with: url).resume()