Loading/Downloading image from URL on Swift

前端 未结 30 2503
感动是毒
感动是毒 2020-11-21 05:39

I\'d like to load an image from a URL in my application, so I first tried with Objective-C and it worked, however, with Swift, I\'ve a compilation error:

30条回答
  •  臣服心动
    2020-11-21 06:04

    If you just want to load image (Asynchronously!) - just add this small extension to your swift code:

    extension UIImageView {
        public func imageFromUrl(urlString: String) {
            if let url = NSURL(string: urlString) {
                let request = NSURLRequest(URL: url)
                NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) {
                    (response: NSURLResponse?, data: NSData?, error: NSError?) -> Void in
                    if let imageData = data as NSData? {
                        self.image = UIImage(data: imageData)
                    }
                }
            }
        }
    }
    

    And use it this way:

    myImageView.imageFromUrl("https://robohash.org/123.png")
    

提交回复
热议问题