How to load image in swift using Alamofire

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

Leave a Comment

tech