Search code examples
swift3session-cookiesalamofire

how to set session & cookie and store it and use it with Alamofire , Swift 3


please someone give me some kind direction , I am totally new in this. I am making an app which will have login option. Once I login I want to keep the session stored so that I don't have to login again and again, until I logout & destroy the session . I am using Alamofire & SwiftyJSON for this app. Here is my code when login btn pressed

    @IBAction func loginBtnPressed(_ sender: AnyObject) {

    let userID = self.userName.text! as String
    let password = self.passwordText.text! as String

    if userID.isEmpty || password.isEmpty {
        showMessage(myMessage: "username & password required")
        return
    }

    let postsEndpoint: String = "http://xxx/api/login/"
    let newPost = ["username": userID, "password": password] as [String : Any]

    Alamofire.request(postsEndpoint, method: .post, parameters: newPost, encoding: URLEncoding.httpBody)
        .responseJSON { response in
            guard response.result.error == nil else {
                // got an error in getting the data, need to handle it
                print("error calling GET on /posts/1")
                print(response.result.error!)
                return
            }
            if let value: AnyObject = response.result.value as AnyObject? {
                // handle the results as JSON, without a bunch of nested if loops
                let post = JSON(value)
                print("The User is: " + post.description)

                let username = post["display_name"].string
                if  ( username != nil ) {
                   // to access a field:
                   // print("The title is: " + username!)

                    let sb: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
                    let controllerLogin : UIViewController = sb.instantiateViewController(withIdentifier: "logInSB")
                    self.present(controllerLogin, animated: true, completion: nil)

                    } else {
                      self.showMessage(myMessage: "wrong username & password")
                }
            }
    }
}

I know what session & cookies are ,If some kind person tell me how can I implement it using Alamofire & Swift it would be life saver for me . I am searching it on the net but could not find any suitable answer. Thank You in advance.


Solution

  • solved it by myself . here at my loginBtnPressed function I set some keys like this

    UserDefaults.standard.set(post["user_id"].int, forKey: "user_id")
    UserDefaults.standard.set(post["user_email"].stringValue, forKey: "user_email")
    UserDefaults.standard.set(post["display_name"].stringValue, forKey: "display_name")
    UserDefaults.standard.synchronize()
    

    and finally in the AppDelegate I checked and called it like this below

     func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
    
        UIApplication.shared.statusBarStyle = .lightContent
    
        let getUserID = UserDefaults.standard.string(forKey: "user_id")
    
        if getUserID != nil {
    
            let sb: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
            let controllerLogin : UIViewController = sb.instantiateViewController(withIdentifier: "SWRevealViewController") as! SWRevealViewController
            self.window?.rootViewController = controllerLogin
        }
    
        return true
    }