Created
July 21, 2016 11:29
-
-
Save artemkrachulov/3069b2efcb8cd547dfd714a936988ac8 to your computer and use it in GitHub Desktop.
Loads image from URL
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
// | |
// UIImage+loadFromURL.swift | |
// | |
// Created by Artem Krachulov | |
// Copyright (c) 2016 Artem Krachulov. All rights reserved. | |
// http://www.artemkrachulov.com | |
// | |
import UIKit | |
extension UIImage { | |
/// Loads image from URL. When load finished will execute block object. This block has no return value and takes a single UIImage argument that replesent loaded image in UIImage object | |
/// | |
/// Usage: | |
/// | |
/// var imageView = UIImageView(frame: CGRectMake(0, 0, 500, 500)) | |
/// | |
/// UIImage.loadFromURL("__URL__", | |
/// completion: { (image) -> () in | |
/// imageView.image = image | |
/// } | |
/// ) | |
public class func loadFromURL(url: String, completion: (UIImage)->()) -> UIImage? { | |
guard !url.isEmpty else { | |
return nil | |
} | |
guard let url = NSURL(string: url) else { | |
return nil | |
} | |
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), { | |
if let data = NSData(contentsOfURL: url) { | |
dispatch_async(dispatch_get_main_queue(), { | |
if let image = UIImage(data: data) { | |
completion(image) | |
} | |
}) | |
} | |
}) | |
return nil | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment