ios - 使用 Firebase 3 和 Swift 注销用户仍然显示 `currentUser`

标签 ios swift xcode firebase firebase-authentication

我正尝试在我的 iOS 应用程序中使用 Firebase 3 注销用户。这是我的代码:

do {

        databaseReference.child("Users").child(CUUID!).removeAllObservers()

        try FIRAuth.auth()?.signOut()

        print("FIRUSER - \(FIRAuth.auth()?.currentUser)")

        self.performSegueWithIdentifier("logOutSegue", sender: self)

    } catch let logOutError {

        print("Error Logging User Out - \(logOutError)")
    }

我想做的是,如果用户成功注销,则继续返回登录屏幕。为了检查用户是否已注销,我打印 currentUser 以查看是否还有用户。我点击了 logOut 按钮,segue 开始工作(没有捕获 -> 没有错误),但是当 print("FIRUSER -\(FIRAuth.auth()?.currentUser)") 代码运行,我仍然得到一个 currentUser。 为什么用户没有被注销?

最佳答案

try FIRAuth.auth()?.signOut()signOut() 上使用 cmd+click,您将被引导到它的文档,在那里你会看到


  • @param listener The block to be invoked. The block is always invoked asynchronously on the main thread, even for it's initial invocation after having been added as a listener.

  • @remarks The block is invoked immediately after adding it according to it's standard invocation semantics, asynchronously on the main thread.


异步 这意味着您注销用户的查询被加载到网络链接中的单独线程中,这需要时间(可能只有几毫秒,但仍然......)和您的 print 行甚至在用户注销之前就执行了。这就是为什么您仍然从 firebase 收到 currentUser 的原因...:)

尝试在执行 segue 后迁移到的类的 viewWillAppear(animated:Bool) 中打印 currentUser,如果它退出时没有捕获任何错误,打印行必须显示为零。

PS:- 假设 如果 signOut() 函数有一个 completionBlock: ,并且您尝试在那里打印 currentUser ,您可能会发现 nil,并可能使您的应用程序崩溃……同样,这只是假设

顺便说一句:- 获取当前用户的最佳方式是在 Auth 对象上设置一个监听器

  FIRAuth.auth()?.addAuthStateDidChangeListener { auth, user in
          if let user = user {
              // User is signed in.
           } else {
             // No user is signed in.
          }
    }

Firebase 文档:- Get Current User - Firebase Docs

关于ios - 使用 Firebase 3 和 Swift 注销用户仍然显示 `currentUser`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39169447/

相关文章:

ios - Xcode 6 从 UIViewController 访问 UIApplication

iphone - Instruments VM 跟踪器为空

ios - 在 View 上动画 UIIMageView Alpha 确实加载

iphone - 从字典中的数组中删除与搜索词匹配的所有值(字符串)?

ios - 如何捕获在 iOS 模拟器中抛出的 NSError 实例

ios - 获取 Firebase 文档对象作为 Swift 对象

ios - 单击 DatePicker 时 UITapGestureRecognizer 不工作

Swift Cloud Firestore 自定义对象映射

ios - 单例 View Controller

xcode - 为什么 Xcode 4.3 将 @interface ClassName() 放在实现文件中?