Skip to content

Instantly share code, notes, and snippets.

@daehn
Last active August 29, 2015 14:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save daehn/471f1fe262234ba80e0f to your computer and use it in GitHub Desktop.
Save daehn/471f1fe262234ba80e0f to your computer and use it in GitHub Desktop.
Small UIImageView extension and download helper to quickly set a user picture from www.uifaces.com on a UIImageView
import UIKit
typealias JSON = [String: AnyObject]
public typealias ImageRequestCompletion = (UIImage?, NSError?) -> Void
public enum UserImageSize: String {
case Epic = "epic"
case Big = "bigger"
case Normal = "normal"
case Tiny = "mini"
}
public class ImageDownloader: NSObject {
private static let uiFacesURL = NSURL(string: "http://uifaces.com/api/v1/random")!
public class func getUserImage(size: UserImageSize = .Normal, completion: ImageRequestCompletion) {
let task = NSURLSession.sharedSession().dataTaskWithURL(uiFacesURL) { data, _, error in
if error != nil {
completion(nil, error)
}
var jsonError: NSError? = nil
let json = NSJSONSerialization.JSONObjectWithData(data, options: .MutableLeaves, error: &jsonError) as? JSON
if jsonError != nil {
completion(nil, jsonError)
}
if let json = json, paths = json["image_urls"] as? JSON, path = paths[size.rawValue] as? String, url = NSURL(string: path) {
self.getImage(url, completion: completion)
} else {
completion(nil, NSError(domain: "Error parsing JSON data", code: 0, userInfo: nil))
}
}
task.resume()
}
private class func getImage(url: NSURL, completion: ImageRequestCompletion) {
let task = NSURLSession.sharedSession().dataTaskWithURL(url) { data, _, error in
if let data = data, image = UIImage(data: data) {
completion(image, nil)
} else {
completion(nil, error)
}
}
task.resume()
}
}
public extension UIImageView {
convenience init(size: UserImageSize) {
self.init()
loadUserImage(size)
}
func loadUserImage(size: UserImageSize) {
ImageDownloader.getUserImage(size: size) { image, error in
if error != nil {
println("Error getting image: \(error)")
} else {
dispatch_async(dispatch_get_main_queue()) {
self.image = image
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment