全原生,无添加
extension UIImageView{
func downloadedFrom(imageurl : String){
if imageurl.isEmpty {
return
}
let newUrl = imageurl.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
//创建URL对象
let url = URL(string: newUrl!)!
//创建请求对象
let request = URLRequest(url: url)
let session = URLSession.shared
let dataTask = session.dataTask(with: request, completionHandler: {
(data, response, error) -> Void in
if error != nil{
print(error.debugDescription)
}else{
//将图片数据赋予UIImage
let img = UIImage(data:data!)
// 这里需要改UI,需要回到主线程
DispatchQueue.main.async {
self.image = img
}
}
}) as URLSessionTask
//使用resume方法启动任务
dataTask.resume()
}
func dowloadFromServer(url: URL, contentMode mode: UIView.ContentMode = .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: UIView.ContentMode = .scaleAspectFit) {
guard let url = URL(string: link) else { return }
dowloadFromServer(url: url, contentMode: mode)
}
}