-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathUIImageView.swift
More file actions
49 lines (32 loc) · 1.27 KB
/
Copy pathUIImageView.swift
File metadata and controls
49 lines (32 loc) · 1.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
//
// UIImageView.swift
//
//
// Created by Yoel Lev on 3/13/17.
// Copyright © 2017 YoeLevDevelopment. All rights reserved.
//
import UIKit
let imageCache = NSCache<AnyObject, AnyObject>()
extension UIImageView {
//fetch image profile from a URL Using URLSession and DispatchQueue main async
func loadImageUsingCacheWithUrlString(urlString:String){
self.image = nil
//check cache for image first
if let cacheImage = imageCache.object(forKey: urlString as AnyObject) as? UIImage {
self.image = cacheImage
return
}
//otherwise fire off a new download
let url = URL(string: urlString)
let task = URLSession.shared.dataTask(with: url!, completionHandler: { (data, response, error) in
if error != nil { print(error!); return}
DispatchQueue.main.async {
if let downloadedImage = UIImage(data:data!){
imageCache.setObject(data! as AnyObject, forKey: urlString as AnyObject)
self.image = downloadedImage
}
}
})
task.resume()
}
}