Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Session management using Alamofire

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.

like image 436
user462455 Avatar asked Nov 06 '15 03:11

user462455


1 Answers

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.

like image 168
Quang Hà Avatar answered Sep 28 '22 01:09

Quang Hà