swift+moya URLCahe
1、定义获取缓存策略的接口
import Foundation protocol CachePolicyGettable { var cachePolicy: URLRequest.CachePolicy {get} }
2、TargetType 实现该接口
extension MoyaAPI: TargetType, CachePolicyGettable { var cachePolicy: URLRequest.CachePolicy { switch self { case .featured,.pizza,.categories: return .reloadIgnoringLocalCacheData } } ... }
3、实现PluginType
extension MoyaAPI: TargetType, CachePolicyGettable { var cachePolicy: URLRequest.CachePolicy { switch self { case .featured,.pizza,.categories: return .reloadIgnoringLocalCacheData } }
4、应用PluginType
let MoyaAPIPrivider = MoyaProvider<MoyaAPI>(plugins: [CachePolicyPlugin()]) func all() -> Observable<[FeaturedViewModel]> { let networkData = MoyaAPIPrivider.rx.request(.featured) .filterSuccessfulStatusCodes() .debug() .mapArray(Featured.self) .map{ item -> [FeaturedViewModel] in var viewModels: [FeaturedViewModel] = [] for model in item { try! model.createOrUpdate() let viewModel = FeaturedViewModel(model: model) viewModels.append(viewModel) } return viewModels }.asObservable() }