Search code examples
iosswift3userdefaults

How Keep session in Swift 3.0 using UserDefaults.standard?


I have two(2) swift 3.0 files.

Edited:

My goal is to keep the ViewController active/appear after login is success. And I want to keep LoginVC active when logout button hit.

Everything works fine such as posting and read json data.

Edited:

ViewController successfully active when loggedin, but when i hit logout button, stop and build it again, ViewController still not dismiss. It should be redirect to LoginVC.

I think maybe something wrong with my UserDefaults.standard code.

My code as below

ViewController.swift

import UIKit
class ViewController: UIViewController {

    override func viewDidLoad() { super.viewDidLoad() }

    override func viewDidAppear(_ animated: Bool) {

        let isUserLoggedIn = UserDefaults.standard.bool(forKey: "isUserLoggedIn")
        if(!isUserLoggedIn){
            self.performSegue(withIdentifier: "loginview", sender: self)
        }
    }
    @IBAction func logoutData(_ sender: Any) {
        UserDefaults.standard.set(true, forKey: "isUserLoggedIn");
        UserDefaults.standard.synchronize();
        self.performSegue(withIdentifier: "loginview", sender: self)
    }
}

LoginVC.swift

import UIKit
class LoginVC: UIViewController {
    @IBOutlet var _login: UITextField!
    @IBOutlet var _pass: UITextField!
    var login: String!
    var pass: String!

    override func viewDidLoad() { super.viewDidLoad() }

    @IBAction func loginData(_ sender: Any) {  
        login = _login.text
        pass  = _pass.text

        if(login == "" || pass == "") {
            return
        }
        else {
            let url     = URL(string: "http://localhost/login.php")
            let session = URLSession.shared

            let request = NSMutableURLRequest(url: url! as URL)
            request.httpMethod = "POST"

            let paramToLogin = "login=\(login!)&pass=\(pass!)"
            request.httpBody = paramToLogin.data(using: String.Encoding.utf8)

            let task = session.dataTask(with: request as URLRequest, completionHandler: {
                (data, response, error) in
                if error != nil {
                    return
                }
                else {
                    do {
                        if let json = try JSONSerialization.jsonObject(with: data!) as? [String: String]
                        {
                            DispatchQueue.main.async {
                                let success  = Int(json["message"]!)

                                if(success == 1){
                                    UserDefaults.standard.set(true, forKey: "isUserLoggedIn")
                                    UserDefaults.standard.synchronize();
                                    self.dismiss(animated: true, completion: nil)
                                    return
                                }
                            }
                        }
                    }
                    catch { }
                }
            })
            task.resume()
        }
    }
}

Solution

  • In your code during Logout also the value "true" is storing in UserDefaults. I think this may be the issue.