Swift 3: Display Image from URL

后端 未结 9 1878
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:42

    Use this extension and download image faster.

    extension UIImageView {
        public func imageFromURL(urlString: String) {
    
            let activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: .gray)
            activityIndicator.frame = CGRect.init(x: 0, y: 0, width: self.frame.size.width, height: self.frame.size.height)
            activityIndicator.startAnimating()
            if self.image == nil{
                self.addSubview(activityIndicator)
            }
    
            URLSession.shared.dataTask(with: NSURL(string: urlString)! as URL, completionHandler: { (data, response, error) -> Void in
    
                if error != nil {
                    print(error ?? "No Error")
                    return
                }
                DispatchQueue.main.async(execute: { () -> Void in
                    let image = UIImage(data: data!)
                    activityIndicator.removeFromSuperview()
                    self.image = image
                })
    
            }).resume()
        }
    }
    

提交回复
热议问题