用户关闭应用程序时如何保持登录状态?斯威夫特4

时间:2018-08-29 22:18:56

标签: ios swift

我用Alamofire登录后,一切正常,但是在关闭时我尽一切努力使应用程序保持登录状态,但是我做不到。注意:我仍然没有退出功能

这是我的代码

import Alamofire
import UIKit
import AccountKit
import AlamofireObjectMapper
import Toast_Swift
import JGProgressHUD
import PasswordTextField

class ViewController: UIViewController, AKFViewControllerDelegate, UITextFieldDelegate  {
    @IBOutlet weak var txtmail: DesignableTextField!
    @IBOutlet weak var txtcontrasena: DesignableTextField!
    @IBOutlet weak var txtversion: UILabel!
    @IBOutlet weak var btnlogin2: RoundedBorderButton!

    @IBAction func textFieldPrimaryAction(_ sender: Any) {
        login(email: txtmail.text!,password: txtcontrasena.text!)
    }

    var accountKit: AKFAccountKit!

    override func viewDidLoad() {
        super.viewDidLoad()
        btnlogin2.setTitle("INGRESAR", for: .normal)

        //Init Account Kit
        if accountKit == nil {
            self.accountKit = AKFAccountKit(responseType: .accessToken)
        }

        func version() -> String {
            let dictionary = Bundle.main.infoDictionary!
            let version = dictionary["CFBundleShortVersionString"] as! String
            //let build = dictionary["CFBundleVersion"] as! String
            return "\(version)"
        }

        txtversion.text = "Ver."+" "+version()

        let backgroundImage = UIImageView(frame: UIScreen.main.bounds)
        backgroundImage.image = UIImage(named: "background.png")
        backgroundImage.contentMode = UIViewContentMode.scaleAspectFill
        self.view.insertSubview(backgroundImage, at: 0)
    }

    //Funcion Login
    func login (email:String,password:String){
        let hud = JGProgressHUD(style: .dark)
        hud.textLabel.text = "Cargando"
        hud.show(in: self.view)

        let parameters: Parameters = ["email": email as Any,
                                      "password": password as Any,
                                      "businessId": 0,
                                      "tokenFirebase": "string"]

        Alamofire.request("http://00.00.00.00.00.00.00" , method: .post, parameters: parameters , encoding: JSONEncoding.default).validate().responseObject { (response :DataResponse<Result<User>>  )in
            switch response.result {
            case .success:
                let result = response.result.value
                print (result?.message as Any)
                //print(response.result.value?.message!)

                self.showProgress(hud: hud, message: "Success", indicator: true)

                DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
                    self.performSegue(withIdentifier: "reveal", sender: self)
                }
            case .failure(let error):
                print (error)
                switch response.response?.statusCode{
                case 400:
                    self.showProgress(hud: hud, message: "Datos inválidos", indicator: false )
                    break
                case 401:
                    self.showProgress(hud: hud, message: "Credenciales inválidas", indicator: false)
                    break
                default: break
                }
            }
        }
    }

    func showProgress(hud: JGProgressHUD, message:String, indicator: Bool) {
        UIView.animate(withDuration: 1, animations: {
            hud.textLabel.text = message
            hud.detailTextLabel.text = nil
            if indicator {
                 hud.indicatorView = JGProgressHUDSuccessIndicatorView()
            }else{
                hud.indicatorView = JGProgressHUDErrorIndicatorView()
            }

            hud.dismiss(afterDelay: 2)
        })
    }

    @IBAction func btnlogin(_ sender: Any) {
        login(email: txtmail.text!,password: txtcontrasena.text!)
    }

    //Button Register

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)

        if (accountKit.currentAccessToken != nil) {
            //print("User already logged in, go to the home screen")
            DispatchQueue.main.async(execute: {
                self.performSegue(withIdentifier: "loginview", sender: self
                )
            })
        }
    }

1 个答案:

答案 0 :(得分:0)

该应用将不会保持登录状态,您必须存储用于跟踪该数据的数据,您可以将用户电子邮件和密码存储在keyChain内,或者将bool值存储在userDefaults内,以检查AppDelegate内的内容didFinishLaunchingWithOptions在应用打开并导航到适当的VC时

if loggedIn
{
  self.window?.rootViewController = homeVC
}
else {
  self.window?.rootViewController = loginVC
}