MoyaCache
示例
要运行示例项目,首先克隆仓库,然后从 Example 目录运行 pod install
。
需求
- iOS 9.0
- Swift 4.2
安装
MoyaCache 通过 CocoaPods 提供。要安装它,只需将以下行添加到您的 Podfile 中
pod 'MoyaCache'
用法
- 实现缓存协议
extension Storable {
typealias CachedResponse = Moya.Response
public var allowsStorage: (Moya.Response) -> Bool {
return { $0.statusCode == 200 }
}
public func cachedResponse(for key: CachingKey) throws -> Moya.Response {
return try Storage<Moya.Response>().object(forKey: key.stringValue)
}
public func storeCachedResponse(_ cachedResponse: Moya.Response, for key: CachingKey) throws {
try Storage<Moya.Response>().setObject(cachedResponse, forKey: key.stringValue)
}
public func removeCachedResponse(for key: CachingKey) throws {
try Storage<Moya.Response>().removeObject(forKey: key.stringValue)
}
public func removeAllCachedResponses() throws {
try Storage<Moya.Response>().removeAll()
}
}
target
选择过期时间
extension StoryAPI: Cacheable {
var expiry: Expiry {
return .never
}
}
- 读取缓存
let cachedResponse = try target.cachedResponse()
- 需要缓存的请求调用
.cache
,普通请求不会缓存
provider.cache.request(target) { result in
}
作者
Pircate, [email protected]
许可证
MoyaCache 在 MIT 许可证下可用。更多信息请参阅 LICENSE 文件。