I try to convert url to UIImage by using following code :
let url = URL(string: "http://www.apple.com/euro/ios/ios8/a/generic/images/og.png")
let sessionTask = URLSession.shared
let request = URLRequest(url: url!)
let task = sessionTask.dataTask(with: request, completionHandler: {(data: Data?, response: URLResponse?, error: Error?) -> Void in
if (error == nil) {
let image: UIImage = UIImage(data: data!)!
}
})
task.resume()
but it's not work for me, if-loop is not complied.
Try this
let url = URL(string:"http://www.apple.com/euro/ios/ios8/a/generic/images/og.png")
if let data = try? Data(contentsOf: url!)
{
let image: UIImage = UIImage(data: data)
}
With Background thread
DispatchQueue.global(qos: .background).async {
do
{
let data = try Data.init(contentsOf: URL.init(string:"url")!)
DispatchQueue.main.async {
let image: UIImage = UIImage(data: data)
}
}
catch {
// error
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With