无法显示Firebase数据库中的用户数据

时间:2018-08-27 14:52:30

标签: swift firebase firebase-realtime-database

我的应用程序能够从Firebase的数据库加载数据,但现在无法显示它。我假设这与Firebase更新有关。我能够通过调用.child(“ users”)。child((currentUser?.uid)!)。child(“ userDetails”)来访问数据,而我的currentUser是Auth.auth()。currentUser。方法改变了吗? iOS应用程序如何从Firebase读取数据?

enter image description here

override func viewDidLoad() {
    super.viewDidLoad()
    let currentUser = Auth.auth().currentUser
    if currentUser == nil {
        self.showMessage(messageToDisplay: "Could not read user details")
        return
    }

    print("User id = \(String(describing: currentUser?.uid))")
    print("User email \(String(describing: currentUser?.email))")
    print("Is email verified \(String(describing: currentUser?.isEmailVerified))")

    var databaseReference:DatabaseReference!
    databaseReference = Database.database().reference()

    databaseReference.child("users").child((currentUser?.uid)!).child("userDetails").observeSingleEvent(of: DataEventType.value) { (snapshot) in

        let userDetailsData = snapshot.value as? NSDictionary
        let firstName = userDetailsData?["firstName"] as? String ?? ""
        let lastName = userDetailsData?["lastName"] as? String ?? ""

        self.fullNameLabel.text = self.fullNameLabel.text! + " " + firstName + " " + lastName
    }

}

我遇到以下错误:

/ users /(省略了用户ID)/ userDetails上的侦听器失败:permission_denied TIC TCP连接失败[9:0x604000169e40]:1:61 Err(61) HTTP加载失败(错误代码:-1004 [1:61]) 任务完成,错误-代码:-1004 遇到网络错误。代码,错误:-1004,错误域= NSURLErrorDomain代码= -1004“无法连接到服务器。”

1 个答案:

答案 0 :(得分:0)

默认情况下,只有经过身份验证的用户才能访问Firebase项目中的数据库:

{
  "rules": {
    ".read": "auth != null",
    ".write": "auth != null"
  }
}

因此,要显示用户数据,您需要更改规则以允许未经身份验证的用户:

{
  "rules": {
    "users": {
      ".read": true,
      ".write": true
    }
  }
}

或在尝试访问用户数据之前对用户进行身份验证:

Auth.auth().signIn(withEmail: email, password: password) { (user, error) in
  if error == nil {
    // Success!
  } else {
    // Sign in failed
  }  
}