我们都知道Swift UIImageView对象是用来加载显示图片的控件,有时候图片是本地的,而有时候图片来源于网络中,那么学会如何使用UIImageView异步加载网络图片并显示图片是至关重要的,下面是小编写的UIImageView extension扩展方法,使用了URLSession对象async异步下载网络图片,并设置到UIImageView对象中,如下:
extension UIImageView { func dowloadFromServer(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() { self.image = image } }.resume() } func dowloadFromServer(link: String, contentMode mode: UIViewContentMode = .scaleAspectFit) { guard let url = URL(string: link) else { return } dowloadFromServer(url: url, contentMode: mode) } }
下面是UIViewController中使用UIImageView扩展方法的示例,当然了,你也可以对上方的代码进行改造,不用使用UIImageView extension扩展方法,先看看小编如何使用UIImageView扩展方法异步加载网络图片吧!
override func viewDidLoad() { super.viewDidLoad() let imageV = UIImageView(frame: CGRect(x: 90, y: 200, width: 200, height: 200)) imageV.layer.borderWidth = 5 imageV.layer.borderColor = UIColor.red.cgColor imageV.dowloadFromServer(link: "https://yt3.ggpht.com/a-/ACSszfFprNp-1Ay1IhDjH4NenwvLItZpPHeJdewulw=s900-mo-c-c0xffffffff-rj-k-no", contentMode: .scaleAspectFill) self.view.addSubview(imageV) }
效果如下图所示: