Como desativar o URLCache completamente com o Alamofire
Usando o Xcode 7.3 iOS 9.2 no Swift, nada daquele horrível Objetivo C. Eu trabalho nisso há um tempo e ando três vezes no quarteirão agora. Eu tentei este post aqui e não funcionouhttp://www.mzan.com/article/32199494-alamofire-how-remove-cache.shtml
Também tentei usar a documentação da Apple, mas isso é tão ruim que não consigo entender se.
Então, o que estou fazendo é fazer duas chamadas da Alamofire para o meu servidor. Um para testar as credenciais das informações de login para ver se a entrada está correta. O segundo é fazer o download e retornar as informações do cliente para visualização. Ambos estão funcionando bem quando chamo pela primeira vez. O problema é que quando eu saio do aplicativo, limpo todas as informações do usuário da página. Mas quando eu faço logon durante a mesma sessão, ele chama o primeiro da direita, portanto, se eu inserir o nome de usuário ou a senha incorretos, ele retornará false, mesmo que eu entre corretamente na primeira vez. Porém, quando faço o download dos dados do cliente, ele mantém o download das informações antigas desde a primeira vez que acessei as informações do usuário. Ele usa o novo nome de usuário e senha, mas ainda baixa o material antigo.
Estas são as minhas funções de login e logout:
//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
}
E estas são as chamadas 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
Código ATUALIZADO: Faz com que o sistema retorne false a partir da resposta Alamofire
//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