Last active
January 14, 2016 20:40
-
-
Save winslowdibona/2bd797c988410aaf33df to your computer and use it in GitHub Desktop.
Basic Async UIImageView
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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