Swift 3: Display Image from URL

后端 未结 9 1883
Happy的楠姐
Happy的楠姐 2020-12-04 22:27

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/         


        
9条回答
  •  没有蜡笔的小新
    2020-12-04 22:49

    Swift

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

    Usage

    Convenience initializer is failable and accepts optional URL – approach is safe.

    imageView.image = UIImage(url: URL(string: "some_url.png"))
    

提交回复
热议问题