How to load image in swift using Alamofire

85,959

Solution 1

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")

Solution 2

I created a Swift version of UIImageView+AFNetworking here : Github.
You don't have to use AFNetworking (and a bridging header) or Alamofire in your project. Just add the file to your project and use it.


Example usage:

myImageView.setImageWithUrl(imageUrl, placeHolderImage: somePlaceHolderImage)

Solution 3

Taken from Alamofire/README.md

"In order to keep Alamofire focused specifically on core networking implementations, additional component libraries have been created by the Alamofire Software Foundation to bring additional functionality to the Alamofire ecosystem.

AlamofireImage - An image library including image response serializers, UIImage and UIImageView extensions, custom image filters, an auto-purging in-memory cache and a priority-based image downloading system."

https://github.com/Alamofire/AlamofireImage

Solution 4

In swift 5 & Alamofire 5,You can use like bellow..

  AF.request( "https://robohash.org/123.png",method: .get).response{ response in

   switch response.result {
    case .success(let responseData):
        self.myImageView.image = UIImage(data: responseData!, scale:1)

    case .failure(let error):
        print("error--->",error)
    }
}

Solution 5

Here's an approach using RxAlamofire:

import Alamofire
import RxAlamofire

extension UIImageView {
    public func imageFromUrl(urlString: String) {
        requestData(.GET, urlString)
            .observeOn(MainScheduler.instance)
            .subscribeNext { self.image = UIImage(data: $0.1) }
    }
}
Share:
85,959
user3728728
Author by

user3728728

Updated on July 09, 2022

Comments

  • user3728728
    user3728728 almost 2 years

    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

  • user3728728
    user3728728 over 9 years
    That was very very helpful, I found that adding the AFNetworking's is much more easy and fast then adding a code to my project, Thank you very much!
  • Mason G. Zhwiti
    Mason G. Zhwiti about 9 years
    Is there any advantage to this, versus using NSURLCache to control the image caching?
  • Mrugesh Tank
    Mrugesh Tank almost 9 years
    Before found your file I need to integrate whole framework for just this file..... big Thanks
  • namanhams
    namanhams almost 9 years
    @MrugeshTank : haha yes, that's the whole point of writing this :D
  • alex
    alex over 8 years
    i am a newbie following an outdated tutorial (raywenderlich.com/85080/beginning-alamofire-tutorial) which i need to convert to the latest swift 2.0+alamofire 3 setup. For this i think i need to install AlomofireImage as well, but how do i do this? The same way as i installed the alamofire?
  • goelv
    goelv over 8 years
    How can I set/reset the cache if I use the file mentioned in the Github link? Is there a max size for this cache?
  • skywinder
    skywinder over 8 years
    1) is not working for Swift 2 2) it's not about Alamofire 3) it's not an answer for the question.
  • kishorer747
    kishorer747 about 8 years
    there is a seperate library AlamofireImage for handling images. It also takes care of cache and lot more options - github.com/Alamofire/AlamofireImage
  • Lukas Batteau
    Lukas Batteau about 8 years
    sendAsynchronousRequest was deprecated in iOS 9. Use NSURLSession.dataTaskWithURL instead, although I would always go for Alamofire, especially RxAlamofire, see my answer below.
  • v01d
    v01d about 8 years
    I tried your approach, but then I get the following error: Use of unresolved identifier 'MainScheduler'. Any clues how to get rid of it?
  • v01d
    v01d about 8 years
    Nevermind, solved the problem. Had to install RxSwift and RxCocoa as RxAlamofire depends on them. Nice solution. Thank you!
  • UKDataGeek
    UKDataGeek almost 8 years
    It looks like this has been removed from the Readme- so is no longer current information
  • mejim707
    mejim707 almost 8 years
    I like the extension solution. Very clean. I'd add though a placeholder image in the extension.
  • hanzolo
    hanzolo almost 8 years
    AlamofireImage has solved the problem for me of caching images fetched via http