简体   繁体   中英

How would I download images from URL's with SDWebImage then append those images to a UIImage Array?

I'm using UIImageView.image in order to change the visible image on my screen.

iv.image = images[index]

The array 'images' is currently filled with local image files. However, I wish to download images from my server and then append them to the array.

private var images = [img1, img2, img3]

I have been recommended using SDWebImage (particularly SDWebImageManager or SDWebImageDownloader) to do this, however, when exploring the download and caching tutorials, all of them downloaded to a UIImageView. I cannot pass in a UIImageView into the .image extension. I couldn't find any tutorials or examples to help me achieve this. I am fairly new to swift so I do not have a vast amount of experience or understanding.

You can donwload image Async without any library as well.

Following will create a extension for imageView and it will async down image from the server just pass the respective url as parameter it will return an image.

extension UIImageView {
  public func imageFromServerURL(urlString: String) {
    URLSession.shared.dataTask(with: NSURL(string: urlString)! as URL, completionHandler: { (data, response, error) -> Void in
        if error != nil {
            print(error!)
            return
        }
        DispatchQueue.main.async(execute: { () -> Void in
            if let imageData = data {
                let image = UIImage(data: imageData)
                self.image = image
            }
        })            
    }).resume()
  }
}

// And you can call like this where ever required

cell.cellImageView.imageFromServerURL(urlString: banner.imageURL)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM