如何使用UserDefaults.standard在Swift 3.0中保持会话?

时间:2017-01-18 03:19:19

标签: ios swift3 userdefaults

我有两(2)个swift 3.0文件。

编辑:

我的目标是在登录成功后保持ViewController活动/显示。 我想在注销按钮命中时保持LoginVC处于活动状态。

一切正常,例如发布和阅读json数据。

编辑:

ViewController在登录时成功激活,但是当我点击退出按钮,停止并再次构建它时,ViewController仍然没有被忽略。它应该重定向到LoginVC

我认为我的 UserDefaults.standard 代码可能有问题。

我的代码如下

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()
        }
    }
}

2 个答案:

答案 0 :(得分:2)

在Logout期间的代码中,值“true”也存储在UserDefaults中。我认为这可能是个问题。

答案 1 :(得分:1)

let loginStroyBoard = UIStoryboard(name:"Login", bundle: nil)
let businessLoginViewController = loginStroyBoard.instantiateViewController(withIdentifier: "BusinessLoginViewController") as! BusinessLoginViewController
let refreshAlert = UIAlertController(title: "Log Out", message: "Are You Sure to Log Out ? ", preferredStyle: UIAlertControllerStyle.alert)

refreshAlert.addAction(UIAlertAction(title: "Confirm", style: .default, handler: { (action: UIAlertAction!) in
    self.present(businessLoginViewController, animated: true, completion: nil)

DispatchQueue.main.async {
    UserDefaults.standard.removeObject(forKey: "isFirstTime")
    UserDefaults.standard.removeObject(forKey: "isLogIn")
    UserDefaults.standard.removeObject(forKey: "uid")
    UserDefaults.standard.removeObject(forKey: "hash")
    UserDefaults.standard.removeObject(forKey: "storeadminid")
    UserDefaults.standard.removeObject(forKey: "adminhash")
    UserDefaults.standard.removeObject(forKey: "store_id")
    UserDefaults.standard.removeObject(forKey: "isLogIn")
    UserDefaults.standard.removeObject(forKey: "login_id")
    UserDefaults.standard.removeObject(forKey: "password")
    UserDefaults.standard.setValue(false, forKey: "islogout")
    }

    //self.tabBarController?.tabBar.resignFirstResponder()
}))

refreshAlert.addAction(UIAlertAction(title: "Cancel", style: .default, handler: { (action: UIAlertAction!) in
    refreshAlert .dismiss(animated: true, completion: nil)
}))

present(refreshAlert, animated: true, completion: nil)

}

我也会用它来退出..
你可以尝试这个,我将在退出按钮中使用我的单元格。