In Swift 3, I am trying to capture an image from the internet, and have these lines of code:
var catPictureURL = NSURL(fileURLWithPath: \"http://i.imgur.com/
Good solution to extend native functionality by extensions
import UIKit
extension UIImage {
convenience init?(url: URL?) {
guard let url = url else { return nil }
do {
self.init(data: try Data(contentsOf: url))
} catch {
print("Cannot load image from url: \(url) with error: \(error)")
return nil
}
}
}
Convenience initializer is failable and accepts optional URL – approach is safe.
imageView.image = UIImage(url: URL(string: "some_url.png"))