从Firebase设置用户值

时间:2017-04-06 15:24:08

标签: ios swift firebase firebase-realtime-database

我试图初始化User对象中的值,但是从另一个问题来看似乎不可能在那里做 - 现在,尝试在视图控制器中执行相同的操作viewDidLoad,我遇到了另一个错误:

这是我在viewDidLoad中对Firebase的调用(myUser是一个全局变量var myUser:User!):

        let userRef: FIRDatabaseReference = FIRDatabase.database().reference().child("users").childByAutoId()
        let userRefHandle: FIRDatabaseHandle?

        userRefHandle = userRef.observe(.value, with: { (snapshot) -> Void in
            let userData = snapshot.value as! Dictionary<String, AnyObject>
            let id = snapshot.key

            if (FIRAuth.auth()?.currentUser?.uid) != nil {
                if let name = userData["name"] as! String!, name.characters.count > 0 {
                    let handle = userData["handle"] as! String!
                    let gender = userData["gender"] as! String!
                    let profilePicture = userData["profilePicture"] as! String!
                    let uid = userData["uid"] as! String!
                    // let rooms = userData["rooms"] as! [[String : AnyObject]]

                    myUser.uid = uid
                    myUser.uid = handle
                    myUser.uid = name
                    myUser.uid = profilePicture
                    myUser.uid = gender
//                        myUser.rooms = rooms

                } else {
                    print("Error! Could not initialize User data from Firebase")
                }
            }
        })

最终目标是,当用户启动应用时(已经注册并且其信息位于Firebase中),他们的信息将从数据库中提取并设置为User对象,因此值可以在应用程序周围使用(名称,句柄,profilePicture等)。

我在Could not cast value of type 'NSNull' (0x106d378c8) to 'NSDictionary'行上收到错误:let userData = snapshot.value

这是用户在Firebase中的数据:

"users" : {
    "-KgjW9PEvCPVqzn7T5pZ" : {
      "gender" : "male",
      "handle" : "TestHandle123",
      "name" : "Timothy",
      "profilePicture" : "https://graph.facebook.com/*removed*/picture?type=large&return_ssl_resources=1",
      "uid" : "2q4VCKu1e7hiL84ObdzgQcQ0pH63"
    }
}

我想知道这是否是从Firebase设置用户值的正确方法,如果是,如何避免错误?

2 个答案:

答案 0 :(得分:0)

在您的代码中,您正在使用profile

查找个人资料图片
let profilePicture = userData["profile"] as! String!

但在数据中,您有profilePicture

因为您已强制解包,所以在找不到密钥时会出现此错误。

您应该确保在两个地方都使用相同的密钥。如果您遇到数据问题,也可能值得包括默认值

let profilePicture = userData["profile"] as? String ?? "default"

答案 1 :(得分:0)

Since the user is already signed up you should store the key that references to the firebase user (e.g. via NSUserDefaults). In this case "-KgjW9PEvCPVqzn7T5pZ". Use this in the userRef instead of childByAutoId, which would generate a new child location with a new key and doesn't exists yet (hence the NSNull).

    let userRef: FIRDatabaseReference = FIRDatabase.database().reference().child("users").child("-KgjW9PEvCPVqzn7T5pZ")