我们在项目中实现了Moya、RxSwift和Alamofire作为pod。
有人知道你是如何使用这项技术来控制每个url请求的缓存策略的吗?
我已经在Moya的GitHub页面上浏览了相当多的问题,但仍然找不到任何东西。我还尝试使用存储为sampleData文件的实际json响应,如下所示:
var sampleData: Data {
guard let path = Bundle.main.path(forResource: "SampleAggregate", ofType: "txt") else {
return "sampleData".utf8Encoded
}
let sample = try? String(contentsOfFile: path, encoding: String.Encoding.utf8)
return sample!.utf8Encoded
}
提前感谢您的任何专业技巧:)
发布于 2018-01-31 04:35:29
子类MoyaProvider
和compose requestClosure
。
它应该看起来像这样:
final class MyProvider<Target: TargetType>: MoyaProvider<Target> {
public init(
endpointClosure: @escaping EndpointClosure = MoyaProvider.defaultEndpointMapping,
requestClosure: @escaping RequestClosure = MoyaProvider.defaultRequestMapping,
stubClosure: @escaping StubClosure = MoyaProvider.neverStub,
manager: Manager = MoyaProvider<Target>.defaultAlamofireManager(),
plugins: [PluginType] = [],
trackInflights: Bool = false
) {
super.init(
endpointClosure: endpointClosure,
requestClosure: { endpoint, closure in
var request = try! endpoint.urlRequest() //Feel free to embed proper error handling
if request.url == URL(string: "http://google.com")! {
request.cachePolicy = .returnCacheDataDontLoad
} else {
request.cachePolicy = .reloadIgnoringLocalAndRemoteCacheData
}
closure(.success(request))
},
stubClosure: stubClosure,
manager: manager,
plugins: plugins,
trackInflights: trackInflights
)
}
}
发布于 2018-11-12 18:39:18
基于@fredpi的回答,我稍微改进了Moya的缓存插件。下面是我的版本:
import Foundation
import Moya
protocol CachePolicyGettable {
var cachePolicy: URLRequest.CachePolicy { get }
}
final class NetworkDataCachingPlugin: PluginType {
init (configuration: URLSessionConfiguration, inMemoryCapacity: Int, diskCapacity: Int, diskPath: String?) {
configuration.urlCache = URLCache(memoryCapacity: inMemoryCapacity, diskCapacity: diskCapacity, diskPath: diskPath)
}
func prepare(_ request: URLRequest, target: TargetType) -> URLRequest {
if let cacheableTarget = target as? CachePolicyGettable {
var mutableRequest = request
mutableRequest.cachePolicy = cacheableTarget.cachePolicy
return mutableRequest
}
return request
}
}
extension NetworkApiService: CachePolicyGettable {
var cachePolicy: URLRequest.CachePolicy {
switch self {
case .getUserProfile:
return .returnCacheDataElseLoad
default:
return .useProtocolCachePolicy
}
}
}
为了清除缓存,您需要拥有对urlRequest对象的访问权限。如何检索Moya路由的urlRequest可以在following主题中找到。
要清除缓存,可以使用以下代码:
public func clearCache(urlRequests: [URLRequest] = []) {
let provider = ... // your Moya provider
guard let urlCache = provider.manager.session.configuration.urlCache else { return }
if urlRequests.isEmpty {
urlCache.removeAllCachedResponses()
} else {
urlRequests.forEach { urlCache.removeCachedResponse(for: $0) }
}
}
发布于 2020-03-31 21:17:30
如果还想禁用存储的cookies
request.httpShouldHandleCookies = false
https://stackoverflow.com/questions/48516806
复制相似问题