ios - 当用户关闭应用程序时如何保持登录状态? swift 4

标签 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
                )
            })
        }
    }

最佳答案

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

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

关于ios - 当用户关闭应用程序时如何保持登录状态? swift 4,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52086840/

相关文章:

ios - 在 Cordova 插件中以编程方式添加 IOS 功能

android - 绘制固定长度曲线

ios - 不需要/未单击的对象自行增加

ios - swift 3 : Convert Dictionary of String type to Int

ios - 为什么 UIImageview 不是完美的圆?

ios - 如何检查是否有 Chartboost 奖励广告可供展示?

ios - 在苹果应用程序站点关联文件中,为什么 "NOT"不排除提到的路径?

ios - 用户通知中心获取授权选项 Swift 3/4 ios10/11

ios - 如果没有连接、Internet 或其他方式获取 URL 的内容,则 XMLParser 的子类会因 contentsOfURL 初始值设定项而崩溃

iOS/Swift UIImageView (.jpg) 无法识别我的点击手势?