SWIFT:我不能用 URL 下载图像吗?
Posted
技术标签:
【中文标题】SWIFT:我不能用 URL 下载图像吗?【英文标题】:SWIFT: Can't I download image with a URL? 【发布时间】:2017-08-28 05:48:24 【问题描述】:我想从 URL 加载图像。
我的功能:
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage)
if "bigImage" == message.name
print(message.body as? String ?? "nothing")
let urlString = message.body as! String
print(urlString)
imageView.downloadedFrom(link: urlString)
if imageView != nil
我在:imageView.downloadedFrom(link: urlString)
遇到错误
在展开可选值时意外发现 nil
即使我可以收到非零的 message.body。
顺便说一句,我已经打开了 ATS。真的很想知道发生了什么。
func getDataFromUrl(url: URL, completion: @escaping (_ data: Data?, _ response: URLResponse?, _ error: Error?) -> Void)
URLSession.shared.dataTask(with: url)
(data, response, error) in
completion(data, response, error)
.resume()
func downloadImage(url: URL)
print("Download Started")
getDataFromUrl(url: url) (data, response, error) in
guard let data = data, error == nil else return
print(response?.suggestedFilename ?? url.lastPathComponent)
print("Download Finished")
DispatchQueue.main.async() () -> Void in
self.imageView.image = UIImage(data: data)
extension UIImageView
func downloadedFrom(url: URL, contentMode mode: UIViewContentMode = .scaleAspectFit)
contentMode = mode
URLSession.shared.dataTask(with: url) (data, response, error) in
guard
let httpURLResponse = response as? HTTPURLResponse, httpURLResponse.statusCode == 200,
let mimeType = response?.mimeType, mimeType.hasPrefix("image"),
let data = data, error == nil,
let image = UIImage(data: data)
else return
DispatchQueue.main.async() () -> Void in
self.image = image
.resume()
func downloadedFrom(link: String, contentMode mode: UIViewContentMode = .scaleAspectFit)
guard let url = URL(string: link) else return
downloadedFrom(url: url, contentMode: mode)
【问题讨论】:
【参考方案1】:我建议使用图像加载器将图像加载到 UIImageView 中。使用KFSwiftImageLoader
let imageView : UIImageView!
imageView.loadImage(urlString: imageURL)
【讨论】:
以上是关于SWIFT:我不能用 URL 下载图像吗?的主要内容,如果未能解决你的问题,请参考以下文章