菜鸟教程小白 发表于 2022-12-13 13:34:55

ios - 如何使用 Alamofire 完全禁用 URLCache


                                            <p><p>在 Swift 中使用 Xcode 7.3 iOS 9.2 没有那么可怕的 Objective C
我已经为此工作了一段时间,现在已经绕着街区转了三遍。我在这里尝试过这篇文章,但没有用
<a href="http://www.mzan.com/article/32199494-alamofire-how-remove-cache.shtml" rel="noreferrer noopener nofollow">http://www.mzan.com/article/32199494-alamofire-how-remove-cache.shtml</a> </p>

<p>我也尝试过使用苹果文档,但这太糟糕了,我无法理解是否。 </p>

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

<p><strong>这是我的登录和注销功能:</strong></p>

<pre><code>//MARK: ButtonControllers
@IBAction func onLoginClick(sender: AnyObject) {

    errorMessageUI.text = &#34;Checking Creditials&#34;
    email = userNameInput.text!
    password = passwordInput.text!
    buildLoginUrl = checkLoginUrl + emailTag + email + passwordTag + password
    print(buildLoginUrl)
    print(&#34;Login Cred&#34;)
    checkLoginCredentials(buildLoginUrl)
}

@IBAction func onLogoutClick(sender: AnyObject) {

    //null out everything for logout
    email = &#34;&#34;
    password = &#34;&#34;
    self.loginInformation.setObject(self.email, forKey: &#34;email&#34;)
    self.loginInformation.setObject(self.password, forKey: &#34;password&#34;)
    self.loginInformation.synchronize()
    performSegueWithIdentifier(&#34;logoutSegue&#34;, sender: self)
    //self.view = LoginView
}
</code></pre>

<p><strong>这是alamofire的电话</strong></p>

<pre><code>//MARK: Check Credentials Method
//Function to log into the server and retrive data
func checkLoginCredentials(myUrl : String)
{
    Alamofire.request(.GET, myUrl)
      .validate(statusCode: 200..&lt;300)
      .responseString { response in
            print(&#34;Cred Success: \(response.result.isSuccess)&#34;)
            print(&#34;Cred Check: \(response.result.value)&#34;)
            //clear all url chache
            NSURLCache.sharedURLCache().removeAllCachedResponses()

            if response.result.value != nil
            {
                let checker : String = response.result.value!
                if checker.lowercaseString.rangeOfString(&#34;false&#34;) != nil {
                  self.canILogin = false
                  self.errorMessageUI.text = &#34;Wrong username or Password try again&#34;
                }else{
                  self.canILogin = true
                  print(&#34;Downloading Json file for customer info&#34;)
                  self.loadingImage.hidden = false
                  self.downlaodCustomerinfo(self.customerInfoUrl, myUser: self.email, myPass: self.password)
                  //defaults.setBool(textColorSwitch.on, forKey: &#34;DarkText&#34;)
                  self.loginInformation.setObject(self.email, forKey: &#34;email&#34;)
                  self.loginInformation.setObject(self.password, forKey: &#34;password&#34;)
                  self.loginInformation.synchronize()
                }

                print(&#34;Login? &#34; + self.canILogin.description ?? &#34;none&#34; )
            }else
            {
                //Stop the program from downloading anything to avoid crashes
                self.loadingImage.hidden = true
                print(&#34;I cannot download User Info&#34;)
                self.errorMessageUI.text = &#34;A connection error occured&#34;
                //set the json to be empty to avoid a crash
                //reset the json file incase there is anythig in it
                self.downloadJson = &#34;&#34;


            }

    }
}//end of checkLoginCredentials function

//MARK: Download Customer Infoamtion
func downlaodCustomerinfo(myUrl : String, myUser : String, myPass : String)
{

    //clear all url chache
    NSURLCache.sharedURLCache().removeAllCachedResponses()
    print(&#34;Username: &#34; + myUser)
    print(&#34;Password: &#34; + myPass)
    print(&#34;Download Url: &#34; + myUrl )
    print(&#34;Jsonfile before download: &#34; + self.downloadJson)
    Alamofire.request(.GET, myUrl)
      .authenticate(user: myUser, password: myPass)
      .validate(statusCode: 200..&lt;300)
      .responseString { response in
            //print(&#34;Success: \(response.result.isSuccess)&#34;)
            print(&#34;Info Download: \(response.result.value)&#34;)


            if response.result.value != nil{

                self.downloadJson = response.result.value!
                print(&#34;Json file: &#34; + self.downloadJson)
                self.parseCustomerInfo(self.downloadJson)
            }else
            {
                self.loadingImage.hidden = true
                print(&#34;I cannot download User Info&#34;)
                self.errorMessageUI.text = &#34;A connection error occured&#34;
                //set the json to be empty to avoid a crash
                self.downloadJson = &#34;{}&#34;
            }

    }
}//end of download
</code></pre>

<p><strong>更新代码:</strong>
导致系统从 Alamofire 响应中返回 false </p>

<pre><code>//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(&#34;Username for download: &#34; + myUser)
    print(&#34;Password: &#34; + myPass)
    manager.request(.GET, myUrl)
      .authenticate(user: myUser, password: myPass)
      .validate(statusCode: 200..&lt;300)
      .responseString { response in
            //print(&#34;Success: \(response.result.isSuccess)&#34;)
            print(&#34;Info Download: \(response.result.value)&#34;)

            if response.result.value != nil{

                self.downloadJson = response.result.value!
                print(&#34;Json file: &#34; + self.downloadJson)
                self.parseCustomerInfo(self.downloadJson)
            }else
            {
                self.loadingImage.hidden = true
                print(&#34;I cannot download User Info&#34;)
                self.errorMessageUI.text = &#34;A connection error occured&#34;
                //set the json to be empty to avoid a crash
                self.downloadJson = &#34;{}&#34;
            }

    }


}//end of downloadCustomer function
</code></pre></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><p>为什么不配置 session ?如果正确配置 session ,将不会有缓存。</p>

<p>例子:</p>

<pre><code>//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, &#34;https://stackoverflow.com&#34;)
    .validate(statusCode: 200..&lt;300)
    .validate(contentType: [&#34;text/html&#34;])
    .responseString { (response) in
      guard response.result.isSuccess else {
            print(&#34;Error: \(response.result.error)&#34;)
            return
      }
    print(&#34;Result: \(response.result.value)&#34;)
}


//JSON GET request:
self.manager.request(.GET, &#34;someURL&#34;, parameters: params, encoding: .URL, headers: headers)
    .validate(statusCode: 200..&lt;300)
    .validate(contentType: [&#34;application/json&#34;])
    .responseJSON { (response) in
      guard response.result.isSuccess else {
            print(&#34;Error: \(response.result.error)&#34;)
            return
      }

      print(response.result.value as? )
}
</code></pre>

<p><strong>编辑:</strong></p>

<pre><code>let manager = {() -&gt; Alamofire.Manager in
    struct Static {
      static var dispatchOnceToken: dispatch_once_t = 0
      static var instance: Alamofire.Manager!
    }

    dispatch_once(&amp;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, &#34;https://stackoverflow.com&#34;)
    .validate(statusCode: 200..&lt;300)
    .validate(contentType: [&#34;text/html&#34;])
    .responseString { (response) in
      guard response.result.isSuccess else {
            print(&#34;Error: \(response.result.error)&#34;)
            return
      }
    print(&#34;Result: \(response.result.value)&#34;)
}
</code></pre>

<p>附:您还可以查看:</p>

<blockquote>
<p><code>NSURLSessionConfiguration.ephemeralSessionConfiguration()</code> - Returns a
session configuration that uses no persistent storage for caches,
cookies, or credentials.</p>
</blockquote></p>
                                   
                                                <p style="font-size: 20px;">关于ios - 如何使用 Alamofire 完全禁用 URLCache,我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/37535432/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/37535432/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: ios - 如何使用 Alamofire 完全禁用 URLCache