如何使用Alamofire完全禁用URLCache

编程入门 行业动态 更新时间:2024-10-26 13:20:18
本文介绍了如何使用Alamofire完全禁用URLCache的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

使用Xcode 7.3 iOS 9.2全部在Swift中没有那个可怕的目标C 我已经在这方面工作了一段时间并且现在已经三次绕过这个块了。我在这里尝试了这篇文章并且它没有工作 www.mzan/article/32199494-alamofire-how-remove-cache.shtml

Using Xcode 7.3 iOS 9.2 all in Swift none of that horrible Objective C I have been working on this for a while and been around the block three times now. I have tried this post here and it didn't work www.mzan/article/32199494-alamofire-how-remove-cache.shtml

我也尝试使用苹果文档,但这是如此糟糕我无法理解是否。

I have also try to use apple documentation but that is so crappy I cannot make sense of if.

所以我正在做的是对我的服务器进行两次Alamofire调用。一个用于测试登录信息的凭据以查看输入是否正确。第二种是下载并返回客户信息以供查看。当我第一次打电话时,两者都工作正常。问题是当我注销应用程序时,我清除了页面中的所有用户信息。但是当我在同一个会话期间登录时,它会调用第一个,所以如果我输入了错误的用户名或密码,即使我第一次正确登录,它也会返回false。但是当我下载客户数据时,它会在我第一次访问用户信息时不断下载旧信息。它使用新的用户名和密码,但仍会下载旧的东西。

So what I am doing is making two Alamofire calls to my server. One to test the credentials of the login information to see if the input is right. The second is to download and return the customer information for there viewing. Both are working fine when I call it the first time. The problem is when I logout of the app i clear all the user information from the page. But when I logbook in during the same session, it calls the first one right so if I put in the wrong username or password it returns false even if I login correctly the first time. But when I download the customer data, it keeps downloading the old information from the first time I accessed the user information. It uses the new username and password but still downloads the old stuff.

这是我的登录和退出功能:

//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回复中返回false

UPDATED Code: Cause the system to return false from the Alamofire response

//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

推荐答案

为什么不配置会话?如果正确配置会话,则不会进行缓存。

Why are you not configuring the session? If you configure the session correctly, there will be no caching.

示例:

//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, "stackoverflow") .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, "stackoverflow") .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)") }

PS您还可以查看:

NSURLSessionConfiguration.ephemeralSessionConfiguration() - 返回会话配置,对缓存, cookie或凭据不使用持久存储。

NSURLSessionConfiguration.ephemeralSessionConfiguration() - Returns a session configuration that uses no persistent storage for caches, cookies, or credentials.

更多推荐

如何使用Alamofire完全禁用URLCache

本文发布于:2023-11-26 02:00:32,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1632198.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何使用   Alamofire   URLCache

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!