Monday, May 9, 2016

Download Image from URL

Synchronously

Swift 2.2

let url = NSURL(string: 
"http://www.awwwards.com/awards/images/2014/07/UX-design-resources-09.jpg")

if let data = NSData(contentsOfURL: url!) {
    WebImageView.image = UIImage(data: data)
}

Swift 3.0

let url = URL(string: 
"http://www.awwwards.com/awards/images/2014/07/UX-design-resources-09.jpg")

if let data = try? Data(contentsOf: url!) {
    WebImageView.image = UIImage(data: data)
}

Asynchronously

Swift 3.0

let url = URL(string: 
"http://www.awwwards.com/awards/images/2014/07/UX-design-resources-09.jpg")

let task = URLSession.shared.dataTask(with: url!) { data, response, error in
    guard let data = data, error == nil else { return }
    
    DispatchQueue.main.sync() {
        self.WebImageView.image = UIImage(data: data)
    }
}

task.resume()

Tips

You may get an error such as: "App Transport Security has blocked a cleartext HTTP (http://) resource load since it is insecure. Temporary exceptions can be configured via your app's Info.plist file."

To fix this open the Info.plist file in your project and follow these steps:
  1. Click the "+" button on the last item in the list to add a new item.
  2. Add "App Transport Security Settings" and then expand the setting and click the "+" button again to add "Allow Arbitrary Loads". Set this to "YES".

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.

SwiftUI Search & Filter with Combine - Part 3 (iOS, Xcode 13, SwiftUI, 2...

In part 3 of the Searchable video series, I show you how to use Combine in #SwiftUI for the search and filter logic connected to the searcha...