[英]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. 我的应用程序中有一个带有本地图像的UIScroll视图。 I want however, that my Images will be downloaded and stored in Cache from a URL. 但是,我想要从URL下载我的图像并将其存储在缓存中。 I have seen several example libraries that do this like sdwebimage, kingfisher etc. but the examples use UITableview and cells. 我已经看到了几个执行此操作的示例库,例如sdwebimage,kingfisher等。但是示例使用UITableview和单元格。 I am using a UIImage Array for my scroll view. 我正在使用UIImage Array作为滚动视图。 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. 我真正想要的是下载并缓存图像并将它们存储在Array IconsArray = [icon1,icon2,icon3]中,其中icon1到icon3是从URL下载的图像。 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: 对于密钥,您可以只使用URL字符串(很简单的解决方案),因此安全地访问图像将如下所示:
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. 正如我所说,这有一些缺点,但这是您所要求的快速实现。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.