简体   繁体   中英

How can I load Images from URL into an UIImage Array and use them in UIScrollView with Swift

I have a working UIScroll view with local Images in my app. I want however, that my Images will be downloaded and stored in Cache from a URL. I have seen several example libraries that do this like sdwebimage, kingfisher etc. but the examples use UITableview and cells. I am using a UIImage Array for my scroll view. What I actually want is that I download and cache my images and store them in a Array IconsArray = [icon1, icon2, icon3] where icon1 to icon3 are the downloaded images from URLs. How would I do this? Any nice tutorials out there or someone kind enough to show a rookie some code?

Thanks in advance

If you are downloading many images you will have memory problems, and your work will also get thrown away when your array goes out of scope, but what you probably would want to do, if you want to implement your proposed solution, is to use a dictionary rather than an array. It'll just make it much easier to find the image you're looking for. So you could implement the dictionary like this:

var images = [String : UIImage]()

For the key you can just use the URL string (easy enough solution) so accessing an image safely would look like this:

let urlString = object.imageUrl.absoluteString //or wherever you're getting your url from
if let img = self.images[urlString] {
    //Do whatever you want with the image - no need to download as you've already downloaded it.
    cell.image = img
} else {
    //You need to download the image, because it doesn't exist in your dict
    ...[DOWNLOAD CODE HERE]...
    //Add the image to your dictionary here
    self.images[object.imageUrl.absoluteString] = downloadedImage
    //And do whatever else you need with it
    cell.image = downloadedImage
}

As I said, this has some downsides, but it's a quick implementation of what you're asking for.

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