Как полностью отключить URLCache с помощью Alamofire
Использование Xcode 7.3 iOS 9.2 все в Swift - ни одна из тех ужасных задач C Я работал над этим некоторое время и трижды обходил квартал. Я попробовал этот пост здесь, и он не работалhttp://www.mzan.com/article/32199494-alamofire-how-remove-cache.shtml
Я также пытался использовать документацию Apple, но это настолько дерьмово, что я не могу понять, если.
Итак, я делаю два звонка Alamofire на мой сервер. Один, чтобы проверить учетные данные для входа в систему, чтобы увидеть, если ввод правильный. Второе - скачать и вернуть информацию о клиенте для просмотра. Оба работают нормально, когда я звоню в первый раз. Проблема в том, что когда я выхожу из приложения, я удаляю всю информацию о пользователе со страницы. Но когда я захожу в систему во время той же сессии, он вызывает первый правильно, поэтому, если я введу неправильное имя пользователя или пароль, он возвращает 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
ОБНОВЛЕННЫЙ Код: Заставить систему возвращать false из ответа 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