如何使用 Alamofire 完全禁用 URLCache
How to disable the URLCache completely with Alamofire
用Xcode7.3iOS9.2都在Swiftnone那个可怕Objective C
我已经为此工作了一段时间,现在已经绕过街区三圈了。我已经在这里 post 试过了,但没有用
http://www.mzan.com/article/32199494-alamofire-how-remove-cache.shtml
我也尝试过使用 apple 文档,但那太糟糕了,我无法理解是否。
所以我正在做的是对我的服务器进行两次 Alamofire 调用。一是测试登录信息的凭据,看输入是否正确。第二个是下载并return客户资料在那里查看。当我第一次调用它时,两者都工作正常。问题是当我注销应用程序时,我清除了页面上的所有用户信息。但是当我在同一个会话中登录时,它会正确调用第一个,所以如果我输入错误的用户名或密码,即使我第一次正确登录,它 returns false。但是当我下载客户数据时,它一直在下载我第一次访问用户信息时的旧信息。它使用新的用户名和密码,但仍会下载旧内容。
这是我的登录和注销函数:
//MARK: ButtonControllers
@IBAction func onLoginClick(sender: AnyObject) {
errorMessageUI.text = "Checking Creditials"
email = userNameInput.text!
password = passwordInput.text!
buildLoginUrl = checkLoginUrl + emailTag + email + passwordTag + password
print(buildLoginUrl)
print("Login Cred")
checkLoginCredentials(buildLoginUrl)
}
@IBAction func onLogoutClick(sender: AnyObject) {
//null out everything for logout
email = ""
password = ""
self.loginInformation.setObject(self.email, forKey: "email")
self.loginInformation.setObject(self.password, forKey: "password")
self.loginInformation.synchronize()
performSegueWithIdentifier("logoutSegue", sender: self)
//self.view = LoginView
}
这是 alamofire 调用
//MARK: Check Credentials Method
//Function to log into the server and retrive data
func checkLoginCredentials(myUrl : String)
{
Alamofire.request(.GET, myUrl)
.validate(statusCode: 200..<300)
.responseString { response in
print("Cred Success: \(response.result.isSuccess)")
print("Cred Check: \(response.result.value)")
//clear all url chache
NSURLCache.sharedURLCache().removeAllCachedResponses()
if response.result.value != nil
{
let checker : String = response.result.value!
if checker.lowercaseString.rangeOfString("false") != nil {
self.canILogin = false
self.errorMessageUI.text = "Wrong username or Password try again"
}else{
self.canILogin = true
print("Downloading Json file for customer info")
self.loadingImage.hidden = false
self.downlaodCustomerinfo(self.customerInfoUrl, myUser: self.email, myPass: self.password)
//defaults.setBool(textColorSwitch.on, forKey: "DarkText")
self.loginInformation.setObject(self.email, forKey: "email")
self.loginInformation.setObject(self.password, forKey: "password")
self.loginInformation.synchronize()
}
print("Login? " + self.canILogin.description ?? "none" )
}else
{
//Stop the program from downloading anything to avoid crashes
self.loadingImage.hidden = true
print("I cannot download User Info")
self.errorMessageUI.text = "A connection error occured"
//set the json to be empty to avoid a crash
//reset the json file incase there is anythig in it
self.downloadJson = ""
}
}
}//end of checkLoginCredentials function
//MARK: Download Customer Infoamtion
func downlaodCustomerinfo(myUrl : String, myUser : String, myPass : String)
{
//clear all url chache
NSURLCache.sharedURLCache().removeAllCachedResponses()
print("Username: " + myUser)
print("Password: " + myPass)
print("Download Url: " + myUrl )
print("Jsonfile before download: " + self.downloadJson)
Alamofire.request(.GET, myUrl)
.authenticate(user: myUser, password: myPass)
.validate(statusCode: 200..<300)
.responseString { response in
//print("Success: \(response.result.isSuccess)")
print("Info Download: \(response.result.value)")
if response.result.value != nil{
self.downloadJson = response.result.value!
print("Json file: " + self.downloadJson)
self.parseCustomerInfo(self.downloadJson)
}else
{
self.loadingImage.hidden = true
print("I cannot download User Info")
self.errorMessageUI.text = "A connection error occured"
//set the json to be empty to avoid a crash
self.downloadJson = "{}"
}
}
}//end of download
更新代码:
导致系统从 Alamofire 响应 return false
//Create a non-caching configuration.
let config = NSURLSessionConfiguration.defaultSessionConfiguration()
config.requestCachePolicy = .ReloadIgnoringLocalAndRemoteCacheData
config.URLCache = nil
//Create a manager with the non-caching configuration that you created above.
let manager = Alamofire.Manager(configuration: config)
print("Username for download: " + myUser)
print("Password: " + myPass)
manager.request(.GET, myUrl)
.authenticate(user: myUser, password: myPass)
.validate(statusCode: 200..<300)
.responseString { response in
//print("Success: \(response.result.isSuccess)")
print("Info Download: \(response.result.value)")
if response.result.value != nil{
self.downloadJson = response.result.value!
print("Json file: " + self.downloadJson)
self.parseCustomerInfo(self.downloadJson)
}else
{
self.loadingImage.hidden = true
print("I cannot download User Info")
self.errorMessageUI.text = "A connection error occured"
//set the json to be empty to avoid a crash
self.downloadJson = "{}"
}
}
}//end of downloadCustomer function
为什么不配置会话?如果您正确配置会话,则不会有缓存。
示例:
//Create a non-caching configuration.
let config = NSURLSessionConfiguration.defaultSessionConfiguration()
config.requestCachePolicy = .ReloadIgnoringLocalAndRemoteCacheData
config.URLCache = nil
//Allow cookies if needed.
config.HTTPCookieStorage = NSHTTPCookieStorage.sharedHTTPCookieStorage()
//Create a manager with the non-caching configuration that you created above.
self.manager = Alamofire.Manager(configuration: config)
//Examples of making a request using the manager you created:
//Regular HTML GET request:
self.manager.request(.GET, "https://whosebug.com")
.validate(statusCode: 200..<300)
.validate(contentType: ["text/html"])
.responseString { (response) in
guard response.result.isSuccess else {
print("Error: \(response.result.error)")
return
}
print("Result: \(response.result.value)")
}
//JSON GET request:
self.manager.request(.GET, "someURL", parameters: params, encoding: .URL, headers: headers)
.validate(statusCode: 200..<300)
.validate(contentType: ["application/json"])
.responseJSON { (response) in
guard response.result.isSuccess else {
print("Error: \(response.result.error)")
return
}
print(response.result.value as? [String: AnyObject])
}
编辑:
let manager = {() -> Alamofire.Manager in
struct Static {
static var dispatchOnceToken: dispatch_once_t = 0
static var instance: Alamofire.Manager!
}
dispatch_once(&Static.dispatchOnceToken) {
let config = NSURLSessionConfiguration.defaultSessionConfiguration()
config.requestCachePolicy = .ReloadIgnoringLocalAndRemoteCacheData
config.URLCache = nil
let cookies = NSHTTPCookieStorage.sharedHTTPCookieStorage()
config.HTTPCookieStorage = cookies
Static.instance = Alamofire.Manager(configuration: config)
}
return Static.instance
}()
manager.request(.GET, "https://whosebug.com")
.validate(statusCode: 200..<300)
.validate(contentType: ["text/html"])
.responseString { (response) in
guard response.result.isSuccess else {
print("Error: \(response.result.error)")
return
}
print("Result: \(response.result.value)")
}
P.S。您还可以查看:
NSURLSessionConfiguration.ephemeralSessionConfiguration()
- Returns a
session configuration that uses no persistent storage for caches,
cookies, or credentials.
用Xcode7.3iOS9.2都在Swiftnone那个可怕Objective C 我已经为此工作了一段时间,现在已经绕过街区三圈了。我已经在这里 post 试过了,但没有用 http://www.mzan.com/article/32199494-alamofire-how-remove-cache.shtml
我也尝试过使用 apple 文档,但那太糟糕了,我无法理解是否。
所以我正在做的是对我的服务器进行两次 Alamofire 调用。一是测试登录信息的凭据,看输入是否正确。第二个是下载并return客户资料在那里查看。当我第一次调用它时,两者都工作正常。问题是当我注销应用程序时,我清除了页面上的所有用户信息。但是当我在同一个会话中登录时,它会正确调用第一个,所以如果我输入错误的用户名或密码,即使我第一次正确登录,它 returns false。但是当我下载客户数据时,它一直在下载我第一次访问用户信息时的旧信息。它使用新的用户名和密码,但仍会下载旧内容。
这是我的登录和注销函数:
//MARK: ButtonControllers
@IBAction func onLoginClick(sender: AnyObject) {
errorMessageUI.text = "Checking Creditials"
email = userNameInput.text!
password = passwordInput.text!
buildLoginUrl = checkLoginUrl + emailTag + email + passwordTag + password
print(buildLoginUrl)
print("Login Cred")
checkLoginCredentials(buildLoginUrl)
}
@IBAction func onLogoutClick(sender: AnyObject) {
//null out everything for logout
email = ""
password = ""
self.loginInformation.setObject(self.email, forKey: "email")
self.loginInformation.setObject(self.password, forKey: "password")
self.loginInformation.synchronize()
performSegueWithIdentifier("logoutSegue", sender: self)
//self.view = LoginView
}
这是 alamofire 调用
//MARK: Check Credentials Method
//Function to log into the server and retrive data
func checkLoginCredentials(myUrl : String)
{
Alamofire.request(.GET, myUrl)
.validate(statusCode: 200..<300)
.responseString { response in
print("Cred Success: \(response.result.isSuccess)")
print("Cred Check: \(response.result.value)")
//clear all url chache
NSURLCache.sharedURLCache().removeAllCachedResponses()
if response.result.value != nil
{
let checker : String = response.result.value!
if checker.lowercaseString.rangeOfString("false") != nil {
self.canILogin = false
self.errorMessageUI.text = "Wrong username or Password try again"
}else{
self.canILogin = true
print("Downloading Json file for customer info")
self.loadingImage.hidden = false
self.downlaodCustomerinfo(self.customerInfoUrl, myUser: self.email, myPass: self.password)
//defaults.setBool(textColorSwitch.on, forKey: "DarkText")
self.loginInformation.setObject(self.email, forKey: "email")
self.loginInformation.setObject(self.password, forKey: "password")
self.loginInformation.synchronize()
}
print("Login? " + self.canILogin.description ?? "none" )
}else
{
//Stop the program from downloading anything to avoid crashes
self.loadingImage.hidden = true
print("I cannot download User Info")
self.errorMessageUI.text = "A connection error occured"
//set the json to be empty to avoid a crash
//reset the json file incase there is anythig in it
self.downloadJson = ""
}
}
}//end of checkLoginCredentials function
//MARK: Download Customer Infoamtion
func downlaodCustomerinfo(myUrl : String, myUser : String, myPass : String)
{
//clear all url chache
NSURLCache.sharedURLCache().removeAllCachedResponses()
print("Username: " + myUser)
print("Password: " + myPass)
print("Download Url: " + myUrl )
print("Jsonfile before download: " + self.downloadJson)
Alamofire.request(.GET, myUrl)
.authenticate(user: myUser, password: myPass)
.validate(statusCode: 200..<300)
.responseString { response in
//print("Success: \(response.result.isSuccess)")
print("Info Download: \(response.result.value)")
if response.result.value != nil{
self.downloadJson = response.result.value!
print("Json file: " + self.downloadJson)
self.parseCustomerInfo(self.downloadJson)
}else
{
self.loadingImage.hidden = true
print("I cannot download User Info")
self.errorMessageUI.text = "A connection error occured"
//set the json to be empty to avoid a crash
self.downloadJson = "{}"
}
}
}//end of download
更新代码: 导致系统从 Alamofire 响应 return false
//Create a non-caching configuration.
let config = NSURLSessionConfiguration.defaultSessionConfiguration()
config.requestCachePolicy = .ReloadIgnoringLocalAndRemoteCacheData
config.URLCache = nil
//Create a manager with the non-caching configuration that you created above.
let manager = Alamofire.Manager(configuration: config)
print("Username for download: " + myUser)
print("Password: " + myPass)
manager.request(.GET, myUrl)
.authenticate(user: myUser, password: myPass)
.validate(statusCode: 200..<300)
.responseString { response in
//print("Success: \(response.result.isSuccess)")
print("Info Download: \(response.result.value)")
if response.result.value != nil{
self.downloadJson = response.result.value!
print("Json file: " + self.downloadJson)
self.parseCustomerInfo(self.downloadJson)
}else
{
self.loadingImage.hidden = true
print("I cannot download User Info")
self.errorMessageUI.text = "A connection error occured"
//set the json to be empty to avoid a crash
self.downloadJson = "{}"
}
}
}//end of downloadCustomer function
为什么不配置会话?如果您正确配置会话,则不会有缓存。
示例:
//Create a non-caching configuration.
let config = NSURLSessionConfiguration.defaultSessionConfiguration()
config.requestCachePolicy = .ReloadIgnoringLocalAndRemoteCacheData
config.URLCache = nil
//Allow cookies if needed.
config.HTTPCookieStorage = NSHTTPCookieStorage.sharedHTTPCookieStorage()
//Create a manager with the non-caching configuration that you created above.
self.manager = Alamofire.Manager(configuration: config)
//Examples of making a request using the manager you created:
//Regular HTML GET request:
self.manager.request(.GET, "https://whosebug.com")
.validate(statusCode: 200..<300)
.validate(contentType: ["text/html"])
.responseString { (response) in
guard response.result.isSuccess else {
print("Error: \(response.result.error)")
return
}
print("Result: \(response.result.value)")
}
//JSON GET request:
self.manager.request(.GET, "someURL", parameters: params, encoding: .URL, headers: headers)
.validate(statusCode: 200..<300)
.validate(contentType: ["application/json"])
.responseJSON { (response) in
guard response.result.isSuccess else {
print("Error: \(response.result.error)")
return
}
print(response.result.value as? [String: AnyObject])
}
编辑:
let manager = {() -> Alamofire.Manager in
struct Static {
static var dispatchOnceToken: dispatch_once_t = 0
static var instance: Alamofire.Manager!
}
dispatch_once(&Static.dispatchOnceToken) {
let config = NSURLSessionConfiguration.defaultSessionConfiguration()
config.requestCachePolicy = .ReloadIgnoringLocalAndRemoteCacheData
config.URLCache = nil
let cookies = NSHTTPCookieStorage.sharedHTTPCookieStorage()
config.HTTPCookieStorage = cookies
Static.instance = Alamofire.Manager(configuration: config)
}
return Static.instance
}()
manager.request(.GET, "https://whosebug.com")
.validate(statusCode: 200..<300)
.validate(contentType: ["text/html"])
.responseString { (response) in
guard response.result.isSuccess else {
print("Error: \(response.result.error)")
return
}
print("Result: \(response.result.value)")
}
P.S。您还可以查看:
NSURLSessionConfiguration.ephemeralSessionConfiguration()
- Returns a session configuration that uses no persistent storage for caches, cookies, or credentials.