HZh
HZh

Reputation: 65

How to assign an image from URL to NSData by swift?

I am new to swift.

I have one code. It encode a local image logo.png to NSData.

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

How to encode an image from a URL to NSData?

Upvotes: 4

Views: 10508

Answers (4)

Gurjinder Singh
Gurjinder Singh

Reputation: 10299

I have done in swift 3.3 and 4. But this will hang UI and result in jerk.

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 {

}

You can also pass image url to dataTask method of URLSession and get data in response. This is best way to avoid jerk in UI. Like below

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()
      }

Upvotes: 0

Amit Sharma
Amit Sharma

Reputation: 1

This one is working in Swift 3.0 Replace the contentsof:forcastURL with contentsOf: forecastURL! as URL

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

Upvotes: -1

Mudith Chathuranga Silva
Mudith Chathuranga Silva

Reputation: 7434

Try this one :-

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

Upvotes: 2

user3400012
user3400012

Reputation:

Replace myURL with the required URL:

let testImage = NSData(contentsOfURL: myURL)

Upvotes: 4

Related Questions