I know this is a slightly open ended / vague question, but any help on how to proceed would be highly appreciated.
What is the best way to implement session management using Alamofire.
Use case: I am implemented an iOS application which requires user authentication (requires user to be logged in) for most of the features. What is the best way to implement that using alamofire.
I can think of the following:
[1] Make a login request. [2] Get the session cookie. [3] Save the cookie and use it for subsequent requests.
What is the best way to do [3] i.e. save the cookie for subsequent requests.
Also what is the best way to do [1] when user, while navigating the app, stumbles / clicks on a feature which requires user authentication.
In my opinion, I used same instance of Manager for all requests:
let cfg = NSURLSessionConfiguration.defaultSessionConfiguration()
let cooks = NSHTTPCookieStorage.sharedHTTPCookieStorage()
var manager: Manager
With login response, API developer should Set-Cookie into header. And you just need to call other requests normally.
If you need to work with one-time login token, you could use this code to put it in all request's header
var authToken : String? {
didSet {
if let _ = authToken {
self.cfg.HTTPAdditionalHeaders = ["auth_token": authToken!]
self.manager = Manager(configuration: cfg)
}else{
self.cfg.HTTPAdditionalHeaders?.removeValueForKey("auth_token")
self.manager = Manager(configuration: cfg)
}
}
}
It's just my opinion. There're many ways to do it better. Thanks.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With