如何在swift中显示来自API的图像?

时间:2016-07-28 18:03:11

标签: ios node.js swift xcode api

我希望能够在Swift中显示我的nodeJS API(http://my_api/getUserImg)发送的图片。 这条特定路线正在返回如下图像:

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

谢谢,

1 个答案:

答案 0 :(得分:2)

您需要创建NSURLSession才能从您的API获取NSData。然后,您可以将该数据放入UIImage并将其显示在UIImageView

完整示例:

@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