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:
- Click the "+" button on the last item in the list to add a new item.
- 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.