AlamofireURLCache5 0.5.0

AlamofireURLCache5 0.5.0

kenshincui 维护。



  • kenshincui

AlamofireURLCache

Build Status Carthage Compatible Weibo

基于 URLCache 的 Alamofire 网络库缓存扩展

功能

  • 缓存数据并刷新
  • 忽略服务器配置
  • 清除缓存

安装

Carthage

要使用 Carthage 将 Alamofire 集成到您的 Xcode 项目中,请在 Cartfile 中指定它

Swift 4 或 Swift 5(Alamofire 版本为 4.x)

github "kenshincui/AlamofireURLCache"

Swift 3(Alamofire版本为3.x)

github "kenshincui/AlamofireURLCache" == 0.1

运行carthage update以构建框架,并将构建的AlamofireURLCache.framework拖入您的Xcode项目。

手动操作

如果您不想使用上述任何依赖项管理器,您可以将AlamofireURLCache手动集成到项目中(只需要将AlamofireURLCache.swift复制到您的项目中)。

用法

缓存和刷新

您可以使用cache()方法为此次请求保存缓存,并设置带有refreshCache参数的请求以重新发起请求并刷新缓存数据。

  • 简单缓存数据
Alamofire.request("https://myapi.applinzi.com/url-cache/no-cache.php").responseJSON(completionHandler: { response in
    if response.value != nil {
        self.textView.text = (response.value as! [String:Any]).debugDescription
    } else {
        self.textView.text = "Error!"
    }
    
}).cache(maxAge: 10)
  • 刷新缓存
Alamofire.request("https://myapi.applinzi.com/url-cache/no-cache.php",refreshCache:true).responseJSON(completionHandler: { response in
    if response.value != nil {
        self.textView.text = (response.value as! [String:Any]).debugDescription
    } else {
        self.textView.text = "Error!"
    }
    
}).cache(maxAge: 10)

忽略服务器端缓存配置

默认情况下,如果服务器已配置缓存头,则使用服务器端配置,但您可以使用自定义缓存年龄并通过设置ignoreServer参数来忽略此配置。

Alamofire.request("https://myapi.applinzi.com/url-cache/default-cache.php",refreshCache:false).responseJSON(completionHandler: { response in
    if response.value != nil {
        self.textView.text = (response.value as! [String:Any]).debugDescription
    } else {
        self.textView.text = "Error!"
    }
    
}).cache(maxAge: 10,isPrivate: false,ignoreServer: true)

清除缓存

有时您需要手动清除缓存而不是刷新缓存数据,这时可以使用 AlamofireURLCache 的 cache cache API。但对于网络请求错误、序列化错误等,我们建议使用 autoClearCache 参数自动忽略错误的缓存数据。

Alamofire.clearCache(dataRequest: dataRequest) // clear cache by DataRequest
Alamofire.clearCache(request: urlRequest) // clear cache by URLRequest

// ignore data cache when request error
Alamofire.request("https://myapi.applinzi.com/url-cache/no-cache.php",refreshCache:false).responseJSON(completionHandler: { response in
    if response.value != nil {
        self.textView.text = (response.value as! [String:Any]).debugDescription
    } else {
        self.textView.text = "Error!"
    }
    
},autoClearCache:true).cache(maxAge: 10)

在使用 AlamofireURLCache 时,我们建议您在任何情况下都添加 autoClearCache 参数。

授权

AlamofireURLCache 发布在 MIT 许可证下。有关详细信息,请参阅 LICENSE