如何通过swift将图像从URL分配给NSData?

时间:2016-01-29 01:55:02

标签: swift nsdata

我是swift的新手。

我有一个代码。它将local image logo.png编码为NSData。

let testImage = NSData(contentsOfFile: NSBundle.mainBundle().pathForResource("logo", ofType: "png")!)

如何将图像从URL编码为NSData?

4 个答案:

答案 0 :(得分:3)

myURL替换为所需的网址:

let testImage = NSData(contentsOfURL: myURL)

答案 1 :(得分:2)

试试这个: -

var image: UIImage?

let imgURL = NSURL(string: "\(yourURL)")
let request: NSURLRequest = NSURLRequest(URL: imgURL!)
let mainQueue = NSOperationQueue.mainQueue()
NSURLConnection.sendAsynchronousRequest(request, queue: mainQueue, completionHandler: { (response, data, error) -> Void in
  if error == nil {
     // Convert the downloaded data in to a UIImage object
     image = UIImage(data: data!)
  } else {
     image = UIImage(named: "JobPlaceholder") // if occurred an error put a placeholder image
  }
})

答案 2 :(得分:0)

我已经在3.3和4中完成了操作,但这会挂起UI并导致混蛋。

do {
      let imgData = try NSData(contentsOf: URL.init(string: "SomeUrl")!, options: NSData.ReadingOptions())
      let image = UIImage(data: imgData as Data)
        DispatchQueue.main.async() { () -> Void in
          completionBlock(image)
   }
} catch {

}

您还可以将图像url传递到URLSession的dataTask方法,并获取数据作为响应。这是避免UI出现混乱的最佳方法。像下面一样

if let url = URL(string: "someUrl") {
   URLSession.shared.dataTask(with: url) { (data, response, error) in
    guard let httpURLResponse = response as? HTTPURLResponse, httpURLResponse.statusCode == 200,
          let mimeType = response?.mimeType, mimeType.hasPrefix("image"),
          let data = data, error == nil,
          let image = UIImage(data: data) else    {
                DispatchQueue.main.async() { () -> Void in
                    completionBlock(nil)
                }
                return
            }
            DispatchQueue.main.async() { () -> Void in
                completionBlock(image)
            }
          }.resume()
      }

答案 3 :(得分:-1)

这个在Swift 3.0中工作 contentsOf:forecastURL替换 contentsof:forcastURL !作为网址

     let forecastURL = NSURL(string: "http://photos.state.gov/libraries/media/788/images/90x90.gif")

    let testImage = NSData (contentsOf: forecastURL! as URL)

    print("data",testImage!)

    let image = UIImage(data: testImage! as Data)
    print("imaGE :-",image!)