2

I'm trying to disable caching when making iOS requests using Alamofire. When I try to make a request to the server and then make a request while authenticated as a different user I get a 304 status code back.

I've tried everything at this link, all of which don't work or result in errors.

The backend is using Express.js to handle requests and Passport.js for user auth.

Is the correct approach to disable caching on Alamofire and on the iOS application? Or is there something I can do to prevent this happening on the backend? Either way I'm not quite sure next steps for how to move forward.

Update

After looking into this issue a little bit more it looks like Alamofire is sending the exact same authentication information even tho the information getting passed into the authentication section is completely different. But if I wait a few minutes and try the request again it updates to the correct auth information. It's almost like the auth information is cached for a few minutes even if you update it in a new request. So you can't change the auth information until it clears out every few minutes or so. Which makes even less sense.

Update 2

Below is my code

func reloadData() {
    print("Reloading data!!")
    let headers: HTTPHeaders = [
        "testvalidationtoken": "test",
        ]

    let keychain = KeychainSwift()

    let email: String = keychain.get("email")!
    let password: String = keychain.get("password")!


    var configuration = URLSessionConfiguration()
    configuration.urlCache = nil
    var manager : SessionManager = SessionManager(configuration: configuration)


    manager.request("http://IPHERE:3000/api/path", headers: headers).authenticate(user: email, password: password).validate().responseJSON { response in
        switch response.result {

        case .success(let value):

            let json = JSON(value)
            print("JSON: \(json)")

            for item in json.array! {

                let title: String? = item["title"].stringValue
                self.titles.append(title!)
                self.colors.append(UIColor.blue)
            }

            self.tableView.reloadData()

        case .failure(let error):
            print ("My Error")
            print (error)
            let alertController = UIAlertController(title: "Error", message: "Error, please try again", preferredStyle: UIAlertControllerStyle.alert)
            let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default) { (result : UIAlertAction) -> Void in
            }
            alertController.addAction(okAction)
            self.present(alertController, animated: true, completion: nil)
        }
    }
}

Update 3

let loginString = String(format: "%@:%@", email, password)
let loginData = loginString.data(using: String.Encoding.utf8)!
let base64LoginString = loginData.base64EncodedString()

print(base64LoginString)

let headers: HTTPHeaders = ["Authorization": "Basic \(base64LoginString)"]

So after using this latest code above to handle HTTP auth I'm still running into problems. When printing base64LoginString on the iOS device it returns one value then when using those headers to send the request to the server authorization = the previous value.

Community
  • 1
  • 1
Charlie Fish
  • 18,491
  • 19
  • 86
  • 179

2 Answers2

1

If you want to completely disable cache in Alamofire you have to create custom manager without urlCache

var configuration = URLSessionConfiguration.default
configuration.urlCache = nil
configuration.httpAdditionalHeaders = SessionManager.defaultHTTPHeaders
var manager : SessionManager = SessionManager(configuration: configuration)

manager.request(...)
kamwysoc
  • 6,709
  • 2
  • 34
  • 48
  • I get an error with that code that says `Use of undeclared type 'Manager'` – Charlie Fish Feb 24 '17 at 07:07
  • please try to change it to `SessionManager`. and of course please `import Alamofire` – kamwysoc Feb 24 '17 at 07:08
  • `Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSURLSessionConfiguration setURLCache:]: unrecognized selector sent to instance` I now get that error at runtime. – Charlie Fish Feb 24 '17 at 07:10
  • what version of Alamofire you have? Could you share your code also? – kamwysoc Feb 24 '17 at 07:13
  • Not sure on the version. My podfile says `pod 'Alamofire', '~> 4.0'` but haven't updated it or anything like that recently. Just edited the question to add the code. When that function gets called it runs fine the first time. Then if I change the email and password in a different function and then run it again the server still thinks it's the first email and password not the new one. If I wait a few minutes before trying again it seems to work. – Charlie Fish Feb 24 '17 at 07:18
  • Ok, I updated my code. Now should be fine, try to create configuration using `URLSessionConfiguration.default` instead `URLSessionConfiguration()` – kamwysoc Feb 24 '17 at 07:51
  • It's logging the following `My Error Error Domain=NSURLErrorDomain Code=-999 "cancelled" UserInfo={NSErrorFailingURLKey=http://IPHERE:3000/api/path, NSLocalizedDescription=cancelled, NSErrorFailingURLStringKey=http://IPHERE:3000/api/path}` – Charlie Fish Feb 24 '17 at 07:52
  • Last thing that you can add is `configuration.httpAdditionalHeaders = SessionManager.defaultHTTPHeaders`. But I think this error is not related with changes in `urlCache` – kamwysoc Feb 24 '17 at 07:57
  • Yeah same problem. Strange thing is that error wasn't happening before. I'm not even sure if it's a caching issue anymore. It seems so strange that if I change the variables `email` and `password` using a different function then recall that function it still uses the old auth information for a few minutes or so. It's almost like it's caching the auth info. Which doesn't seem right. – Charlie Fish Feb 24 '17 at 08:00
  • Maybe try to not use `authenticate` function from Alamofire. Check this: http://stackoverflow.com/a/34457463/5433235 – kamwysoc Feb 24 '17 at 08:02
  • That doesn't work at all with the new version of Swift I guess haha. – Charlie Fish Feb 24 '17 at 08:04
  • Yeah same problem – Charlie Fish Feb 24 '17 at 08:08
0

you can try this:

let cstorage = HTTPCookieStorage.shared
if let cookies = cstorage.cookies(for: url) {
    for cookie in cookies {
        cstorage.deleteCookie(cookie)
    }
}

hope this will help you

lalithkumar
  • 3,480
  • 4
  • 24
  • 40
kobehjk
  • 11
  • 1