删除时调用AuthStateDidChangeListenerHandle

时间:2019-03-26 21:49:04

标签: ios swift firebase firebase-authentication

我正在创建用于Firebase身份验证的登录页面,但是每当我在未登录(例如取消登录操作)的情况下关闭此登录页面时,firebase都会重新打开此ViewController,从而创建循环。

在主视图控制器中,我设置了以下代码:

    var shouldAddHandle: Bool?
    func willDismiss() {
        shouldAddHandle = false
        print("willdismiss")
        NotificationCenter.default.post(name: NSNotification.Name("selectMenu"), object: nil, userInfo: ["row": 0])
    }

    var user: User?
    var authHandle: AuthStateDidChangeListenerHandle?
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        print("willappear")

        if !(shouldAddHandle ?? true) {
            return
        }

        print("willappear2")

        authHandle = Auth.auth().addStateDidChangeListener { (auth, user) in
            if user != nil {
                self.user = user
            } else {
                if let vc = UIStoryboard(name: "Messenger", bundle: Bundle(path: "Storyboards")).instantiateViewController(withIdentifier: "SecurityLogin") as? SecurityLoginVC {
                    if let topVC = vc.topViewController as? SecurityLoginTableVC {
                        topVC.delegate = self
                    }
                    print("present")
                    self.present(vc, animated: true, completion: nil)
                }
            }
        }
    }

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        print("willdisappear")
        if let authHandle = authHandle {
            Auth.auth().removeStateDidChangeListener(authHandle)
        }
    }

我的登录页面viewcontroller看起来像这样:

protocol SecurityLoginTableVCDelegate {
    func willDismiss()
}

class SecurityLoginTableVC: UITableViewController {
    var delegate: SecurityLoginTableVCDelegate?

    override func viewDidLoad() {
        super.viewDidLoad()

        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Cancel", style: .done, target: self, action: #selector(handleCancel(sender:)))
    }

    @objc func handleCancel(sender: UIBarButtonItem) {
        self.delegate?.willDismiss()
        self.dismiss(animated: true)
    }
}

首次加载主视图的控制台输出为:

willappear
willappear2
present
willdisappear

在显示的视图控制器内部单击取消按钮:

willdismiss
willappear
willdisappear
willappear
willappear2
present
willdisappear

出于某种奇怪的原因,WillAppear被调用了两次,并覆盖了我的布尔值shouldAddHandle

0 个答案:

没有答案