boehm_s
boehm_s

Reputation: 5564

How to display image from API in swift?

I want to be able to display the image sent by my nodeJS API (http://my_api/getUserImg) in Swift. This specific route is returning an image like that :

fs.readFile('my_file.jpg', function(err,data) {
  if (err)
    res.json({success: false, message: err});
  res.send(data);`
}

Upvotes: 1

Views: 6753

Answers (1)

MarcJames
MarcJames

Reputation: 189

You need to create an NSURLSession to get the NSData from your API. Then you can put that data into a UIImage and display it in a UIImageView.

Full Example:

@IBOutlet weak var testImageView: UIImageView!

let config = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: config)
if let url = NSURL(string: "http://my_api/getUserImg"){

    let task = session.dataTaskWithURL(url, completionHandler: {data, response, error in

        if let err = error {
            print("Error: \(err)")
            return
        }

        if let http = response as? NSHTTPURLResponse {
            if http.statusCode == 200 {
                let downloadedImage = UIImage(data: data!)
                dispatch_async(dispatch_get_main_queue(), {
                    self.testImageView.image = downloadedImage
                })
            }
        }
   })
   task.resume()
}

Example Project on GitHub

Upvotes: 1

Related Questions