簡體   English   中英

檢查用戶是否存在於 Firebase 中不起作用 - Swift

[英]Checking if User Exists in Firebase doesn't Work - Swift

我在我的 Swift/iOS 項目中使用 Firebase,並嘗試執行檢查以確定用戶在登錄/登錄用戶流程中時數據庫中是否已經存在。

這就是我目前用來檢查用戶是否存在的方法……無論如何,即使我可以直觀地驗證用戶是否在我的數據庫中,我也總是得到用戶不存在的結果。

if let user = Auth.auth().currentUser {
    let ref = self.ref.child("users").child(user.uid)
    ref.observeSingleEvent(of: .value, with: { snapshot in
        self.performSegue(withIdentifier: "GoToMainViewController", sender: nil)
     })

} else {
    self.performSegue(withIdentifier: "GoToProfileCreationViewController", sender: nil)
}

我已經在這里這里的這兩個 SO 線程中嘗試了接受,但始終得到相同的結果。

編輯:這是我的數據庫結構

在此處輸入圖片說明

EDIT2:這是完整的流程,包括我對登錄用戶進行身份驗證的代碼(通過電話號碼)。 在我記錄用戶 ID 的兩個地方,我都得到了登錄 ID。

Auth.auth().signIn(with: credential) { (authResult, error) in
    if let error = error {
        let alert = UIAlertController(title: nil, message: error.localizedDescription, preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "Cancel", style: .cancel) { actions in
        })
        self.present(alert, animated: true)
        return
    }

    let userID = Auth.auth().currentUser?.uid

    print(userID)

    Auth.auth().addStateDidChangeListener { auth, user in
        if user != nil{
            print("user is not nil")
            //self.performSegue(withIdentifier: "GoToJoinChannelsViewController", sender: self)
        }
        else{
            print("user is nil")
            //self.performSegue(withIdentifier: "GoToProfileCreationViewController", sender: nil)
        }
    }

    print(userID)

    //Check if user exists
    if let user = Auth.auth().currentUser {
        let ref = self.ref.child("users").child(user.uid)
        ref.observeSingleEvent(of: .value, with: { snapshot in
            print(snapshot)
            //self.performSegue(withIdentifier: "GoToJoinChannelsViewController", sender: nil)
        })

    } else {
        //self.performSegue(withIdentifier: "GoToProfileCreationViewController", sender: nil)
    }

這是生成的快照的樣子:

Snap (sxQLr6p9meZyQi8p8RPrjVxcUi33) {
    bio = h;
    birthday = "11-Feb-1989";
    firstname = n;
    lastname = n;
}

你將要附加的AUTH狀態改變監聽器的數據庫監聽,一旦用戶通過驗證,以便它只能運行:

Auth.auth().addStateDidChangeListener { auth, user in
  if user != nil {
    let ref = self.ref.child("users").child(user.uid)
    ref.observeSingleEvent(of: .value, with: { snapshot in
      if snapshot.exists() {
        // TODO: a user is signed in and registered, navigate to the next screen for them
        self.performSegue(withIdentifier: "GoToJoinChannelsViewController", sender: nil)
      }
      else {           
        // TODO: a user is signed in and not registered, navigate to the next screen for them
      }
    })
  }
  else{
    self.performSegue(withIdentifier: "GoToProfileCreationViewController", sender: nil)
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM