Reputation: 5564
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
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()
}
Upvotes: 1