且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Firebase +迅速检索用户数据

更新时间:2023-02-01 23:30:36

我已经在 http://www.appcoda.com/firebase/



当我们试图从当前用户获取数据时,添加这段代码下面存储uid(当创建用户帐户时)

pre $ c $ NSUserDefaults.standardUserDefaults()。setValue(result [uid], forKey:uid)

分配变量:

  var CURRENT_USER_REF:Firebase {
let userID = NSUserDefaults.standardUserDefaults()。valueForKey(uid)as!
$ b让currentUser = Firebase(url:\(BASE_REF))。





为函数实现代码:

 < reference> .observeEventType(FEventType.Value,withBlock:{snapshot in 

let currentUser = snapshot.value.objectForKey(username) as!String
< - 您的代码 - >
print(用户名:\(currentUser))
self.currentUsername = currentUser
},withCancelBlock: {error
print(error.description)
})
}



那么我们可以直接淘汰裁判。

I just tried to retrieve data from firebase for my project. For example, display the facebook user name in UILabel. I store the facebook user data like this

then retrieve the data using :

let ref = Firebase(url:"https://<app-name>.firebaseio.com/users/facebook:10207213459687665/name")

ref.observeEventType(.Value, withBlock: { snapshot in

   self.facebookUserName.text = snapshot.value as! String

})

It works perfectly but it is pretty stupid by retrieving user name in a specific path because that could be different facebook user login.

I'm thinking like check the user is logged in and display their name or checking the currentUser or any smarter way to do this? I am not sure how to do that.

I have found an answer in http://www.appcoda.com/firebase/

When we are trying to fetch the data from current user add this code below to store the uid(when creating user account)

NSUserDefaults.standardUserDefaults().setValue(result ["uid"], forKey: "uid")

assign the variable:

var CURRENT_USER_REF: Firebase {
    let userID = NSUserDefaults.standardUserDefaults().valueForKey("uid") as! String

    let currentUser = Firebase(url: "\(BASE_REF)").childByAppendingPath("users").childByAppendingPath(userID)

    return currentUser!
}

implement code for function:

<reference>.observeEventType(FEventType.Value, withBlock: { snapshot in

        let currentUser = snapshot.value.objectForKey("username") as! String
        <--your code-->
        print("Username: \(currentUser)")
        self.currentUsername = currentUser
        }, withCancelBlock: { error in
            print(error.description)
    })
}

Then we could obsolete the ref in a direct path.