NeoImageLoader 1.2.0

NeoImageLoader 1.2.0

测试已测试
Lang语言 SwiftSwift
许可证 Apache 2
发布上次发布2019年3月
SPM支持 SPM

Edison Santiago 维护。



  • Neomode

NeoImageLoader

NeoImageLoader 是一个带有自动管理临时缓存的异步图像加载库。

功能

  • 从远程 URL 异步加载图像
  • 自动缓存所有加载的图像
  • 始终在从远程加载之前尝试从本地缓存加载
  • 缓存过期和删除未使用的单个元素
  • 在 imageView 上显示远程请求的加载指示器

安装

CocoaPods

NeoImageLoader 通过 CocoaPods 提供。只需将 pod 'NeoImageLoader' 添加到您的 Podfile,并运行 pod install

入门

加载图像

加载图像最简单的方法是使用 UIImageView 扩展。此图像将被缓存,后续对同一 URL 的调用将使用本地缓存版本而不是远程。

import NeoImageLoader

imageView.loadImage(
	forUrl: "https://yoururl.com/image.png"
)

您还可以设置一个占位图像、加载图像和完成处理程序(如果您需要在图像加载或未加载时对视图进行某些修改)。

import NeoImageLoader

let loadingStyle = NeoImageLoader.NeoImageLoading()
//The color of the UIActivityIndicatorView show on the image
loadingStyle.loadingColor = UIColor.lightGray
//If we use a large UIImageView maybe it is a good idea to show a large indicator
loadingStyle.largeIndicator = true

imageView.loadImage(
	forUrl: "https://yoururl.com/image.png",
	placeholderImage: UIImage(named: "placeholder"),
	loadingStyle: loadingStyle,
	completion: {
		image, error in
		//Both parameters are optional, bot only one would be set at any time. If one is nil the other is always not nil.	
	}
)

处理错误

完成处理程序将始终返回一个 NeoImageLoaderError 对象。枚举选项是自我解释的:.notFoundLocal、.errorLoadingLocal.invalidImageUrl.errorLoadingRemote(originalError: Error?)。errorLoadingRemote 将返回 URLSessionDataTask 给出的原始错误。

在 UIImageView 之外加载

如果您需要在 ImageView 之外加载图像,可以使用 NeoImageLoader.loadImage(forUrl url: String, completion: @escaping (UIImage?, Error?) -> Void)。图像将被自动缓存,就像在 UIImageView 扩展中一样,您只是不获得与 imageView 相关的功能(占位图像和加载)。

import NeoImageLoader

NeoImageLoader.loadImage(
	forUrl: "https://yoururl.com/image.png",
	completion: {
		image, error in
		//Both parameters are optional, bot only one would be set at any time. If one is nil the other is always not nil.	
	}
)

取消任务

UIImageView 扩展和 NeoImageLoader 上的 loadImage 都返回一个 NeoImageLoader 对象。该对象仅包含一个属性,一个 task: URLSessionDataTask? 对象,该对象包含请求。

请注意,由于请求的异步性质,函数返回时任务属性 将为 nil,并将在网络请求开始时设置。如果图像在本地加载,则任务属性根本不会设置。

如果您需要取消请求,您可以使用 Swift 可选语法,并且只有当任务设置时才取消请求。

import NeoImageLoader

let loader = NeoImageLoader.loadImage(
	forUrl: "https://yoururl.com/image.png"
)

//Some app logic here

//If the loader exists and the tasks exists it will be cancelled. Otherwise, no action and no error will occur
loader?.task?.cancel()

缓存管理

通过 UIImageView 扩展或 NeoImageLoader 函数加载的所有图像都将自动缓存,并且在下一次调用相同的 URL 时的本地图像将被返回。如果图像被缓存,则根本不会进行网络请求。
由于图像是通过URL作为标识进行缓存的,请确保您的应用中加载的所有图像都具有唯一的URL

缓存过期

我们本地跟踪每个图像的最后请求时间戳,凭借这些信息我们可以知道何时可以删除图像。任何连续10天未加载的图像将被删除,目前无法更改此值,尽管我们计划在未来添加此功能。

请注意,这10天的间隔是基于应用使用的,如果您一个月都没有打开应用,图像将不会被删除。

缓存清理每天只进行一次,在后台进行,因此不会占用您的应用资源。

许可证

NeoImageLoader遵循Apache v2许可证。有关更多信息,请参阅LICENSE文件。