How to load image in swift using Alamofire

user3728728 picture user3728728 · Feb 20, 2015 · Viewed 77.5k times · Source

I have a collection view controller, which load image Async by URL. (Something like Instegram) I am looking for the best way to implement the part of the loading image. please tell me what do you think

First way - without any external library:

   let downloadQueue = dispatch_queue_create("com.pro.asyncImages",nil)
    dispatch_async(downloadQueue){

        var data = NSData(contentsOfURL: NSURL(string: pictureUrl!)!)

        var image: UIImage?
        if (data != nil){
            image = UIImage(data: data!)
        }
        dispatch_async(dispatch_get_main_queue()){
            uiImageView.image = image
        }
    }

Second way - using Alamofire (the request belong to Alamofire)

if let  mediaUrl = info.mediaUrl {
        request(.GET,mediaUrl).response(){
            (_, _, data, _) in
            let image = UIImage(data: data! as NSData)
            imageView.image = image
        }
    }

And lastly, I read that AFNetworking, is doing a great job in loading url async to urlImage, Which this is what I want to do.

So is AFNetworking is better for this task? (then Alamofire) and if not, I did not understand how to add AFNetworking to my swift project, beside adding the #import “AFNetworking.h” which files do I need to add?

please explain which method is the best, my needs are performance, accusation, caching. the view collection controller acts like Instegram and is loading images, while scrolling down. I hope I was clear enough about what I need, thank you

Answer

skywinder picture skywinder · Jun 2, 2015

As authors mention in Alamofire README.md:

When should I use AFNetworking?

  • UIKit extensions, such as asynchronously loading images to UIImageView

So answer to your question :

So is AFNetworking is better for this task?

Yes!

But if still want to use vanilla Alamofire project, you can fetch image this way:

   Alamofire.request(.GET, "https://robohash.org/123.png").response { (request, response, data, error) in
        self.myImageView.image = UIImage(data: data, scale:1)
    }

P.S.

But if you just want to load image (of course async) - you don't need to use Alamofire or AFNetworking at all. Just add this small extension in your code:

extension UIImageView {
    public func imageFromUrl(urlString: String) {
        if let url = NSURL(string: urlString) {
            let request = NSURLRequest(URL: url)
            NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) {
                (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in
                self.image = UIImage(data: data)
            }
        }
    }
}

And use it:

myImageView.imageFromUrl("https://robohash.org/123.png")