【问题标题】:Realtime Database permission denied (swift)实时数据库权限被拒绝(swift)
【发布时间】:2022-02-08 02:43:44
【问题描述】:

我想知道玩家是否已经在游戏中,但我对数据库编程完全陌生。我不断收到此错误

2022-02-07 17:32:51.787097+0100 Troeven2.0[64029:2674017] 7.10.0 - [Firebase/Database][I-RDB038012] 位于 / 的侦听器(这里是正确的!用户 id当前用户)失败:permission_denied

更新**和错误处理程序返回:

Error Domain=com.firebase Code=1 "Permission Denied" UserInfo={NSLocalizedDescription=Permission Denied}

**

我觉得这很奇怪,因为用户拥有我所看到的完全权利来写入和读取他自己的数据,规则:

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

我的数据结构如下:

我用来访问的代码是这样的:

func checkIfInGame(completionHandler: @escaping (_ completionHandler: Bool) -> Void) {
    let currentUserID = Auth.auth().currentUser?.uid
    let ref = Database.database().reference().child(currentUserID!).child("gameInfo")
    
    ref.observe(.value , with: { (snapshot) in
        if let directory = snapshot.value as? [String: Any] {
            let gameID = directory["gameID"] as! String
            let isInGame = directory["inGame"] as! String
            var flag = false
            if isInGame == "yes" {
                flag = true
            }
            completionHandler(flag)
        }
    }) { (error) in
        print("error checking in game")
        completionHandler(false)
    }
}

知道我的代码立即打印错误“游戏中的错误检查”也可能很方便 非常感谢任何帮助和时间!

【问题讨论】:

  • 与您的权限问题没有直接关系,但您接下来会遇到这个问题:ref.observe 是一个 异步 函数。您将无法像您尝试做的那样立即从checkIfInGame 返回Bool。查看“回调函数”或“完成处理程序”
  • 这可以解释为什么先打印函数之后的打印语句,感谢您的洞察力!
  • print(error)了吗?这会告诉你到底是什么问题。
  • 另请注意,您在$uid 下拥有的".write": "$uid == auth.uid" 不会做任何事情,因为它会被您拥有的".read": "auth.uid != null" 覆盖而不是/users。见firebase.google.com/docs/database/security/…
  • 我刚刚添加了错误信息!

标签: swift firebase-realtime-database firebase-security


【解决方案1】:

浪费了我一天的愚蠢错误:我没有进入 child("users") 因此没有授予权限。我也切换到 getData,因为我只需要一次被问到的数据......

func checkIfInGame(completionHandler: @escaping (_ completionHandler: Bool) -> Void) {
    guard let currentUserID = currentUser?.uid else {return}
    let ref = Database.database().reference().child("users").child(currentUserID)
    
    ref.child("gameInfo/inGame").getData(completion:  { error, snapshot in
        guard error == nil else {
            print(error!.localizedDescription)
            return;
        }
        let test = snapshot.value as? String ?? "no";
        
        print(test)
    })
}

【讨论】:

    猜你喜欢
    • 2020-10-08
    • 2020-11-25
    • 2018-12-12
    • 2021-05-25
    • 2020-02-04
    • 2018-02-20
    • 1970-01-01
    • 2018-08-02
    相关资源
    最近更新 更多