Skip to content

Instantly share code, notes, and snippets.

@winslowdibona
Last active January 14, 2016 20:40
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save winslowdibona/2bd797c988410aaf33df to your computer and use it in GitHub Desktop.
Save winslowdibona/2bd797c988410aaf33df to your computer and use it in GitHub Desktop.
Basic Async UIImageView
import Foundation
import UIKit
extension UIImageView {
func setImageWithUrlString(urlString : String, placeholderImageFileName : String?){
if let placeholderImageFileName = placeholderImageFileName {
self.setImageOnMainThread(UIImage(named: placeholderImageFileName))
}
let url = NSURL(string: urlString)!
let request = NSMutableURLRequest(URL: url, cachePolicy: .ReturnCacheDataElseLoad, timeoutInterval: 30.0)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { (data, response, error : NSError?) -> Void in
guard let data = data where error == nil else {
print("Error getting image from url \n \(error!)")
return
}
let loadedImage = UIImage(data: data)
self.setImageOnMainThread(loadedImage)
}
task.resume()
}
func setImageOnMainThread(imageToSet : UIImage?) {
if NSThread.isMainThread() {
self.image = imageToSet
} else {
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.image = imageToSet
})
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment