cno*_*oon 42
你有几个选择.
let manager: Manager = {
let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
configuration.URLCache = nil
return Manager(configuration: configuration)
}()
Run Code Online (Sandbox Code Playgroud)
let manager: Manager = {
let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
configuration.requestCachePolicy = .ReloadIgnoringLocalCacheData
return Manager(configuration: configuration)
}()
Run Code Online (Sandbox Code Playgroud)
这两种方法都应该适合你.有关更多信息,我建议您阅读NSURLSessionConfiguration和NSURLCache的文档.另一个很好的参考是关于NSURLCache的 NSHipster文章.
All*_*las 38
这对我有用.
NSURLCache.sharedURLCache().removeAllCachedResponses()
Run Code Online (Sandbox Code Playgroud)
斯威夫特3
URLCache.shared.removeAllCachedResponses()
Run Code Online (Sandbox Code Playgroud)
And*_*rew 30
迅捷3,alamofire 4
我的解决方案是:
为Alamofire创建扩展:
extension Alamofire.SessionManager{
@discardableResult
open func requestWithoutCache(
_ url: URLConvertible,
method: HTTPMethod = .get,
parameters: Parameters? = nil,
encoding: ParameterEncoding = URLEncoding.default,
headers: HTTPHeaders? = nil)// also you can add URLRequest.CachePolicy here as parameter
-> DataRequest
{
do {
var urlRequest = try URLRequest(url: url, method: method, headers: headers)
urlRequest.cachePolicy = .reloadIgnoringCacheData // <<== Cache disabled
let encodedURLRequest = try encoding.encode(urlRequest, with: parameters)
return request(encodedURLRequest)
} catch {
// TODO: find a better way to handle error
print(error)
return request(URLRequest(url: URL(string: "http://example.com/wrong_request")!))
}
}
}
Run Code Online (Sandbox Code Playgroud)
并使用它:
Alamofire.SessionManager.default
.requestWithoutCache("https://google.com/").response { response in
print("Request: \(response.request)")
print("Response: \(response.response)")
print("Error: \(response.error)")
}
Run Code Online (Sandbox Code Playgroud)
func getImage(url: String, completion: @escaping (UIImage?) -> ()) {
let urlRequest = URLRequest(url: URL(string: url)!)
URLCache.shared.removeCachedResponse(for: urlRequest)
//URLCache.shared.removeAllCachedResponses()
Alamofire.request(url).responseData { (dataResponse) in
guard let data = dataResponse.data else {
return completion(nil)
}
completion(UIImage(data: data, scale:1))
}
}
Run Code Online (Sandbox Code Playgroud)