我正在尝试将用户保存到我的firebase数据库。我正在使用FBSDKLoginManager()
创建帐户/登录。创建帐户后,我想将用户存储到我的firebase数据库中。我现在可以登录用户并且他们的电子邮件显示在firebase的Auth选项卡中(参见屏幕截图),但我的updateChildValues
似乎没有任何影响(也见截图)。
我是否将updateChildValues
放在正确的位置?它目前位于signInWithCredential
内。我还必须执行FBSDKGraphRequest
以获取我感兴趣的信息存储在我的firebase数据库中。
func showLoginView() {
let loginManager = FBSDKLoginManager()
loginManager.logInWithReadPermissions(fbPermissions, fromViewController: self, handler: { (result:FBSDKLoginManagerLoginResult!, error:NSError!) -> Void in
if ((error) != nil) {
print("Error loggin in is \(error)")
} else if (result.isCancelled) {
print("The user cancelled loggin in")
} else {
// No error, No cancelling:
// using the FBAccessToken, we get a Firebase token
let credential = FIRFacebookAuthProvider.credentialWithAccessToken(FBSDKAccessToken.currentAccessToken().tokenString)
// using the credentials above, sign in to firebase to create a user session
FIRAuth.auth()?.signInWithCredential(credential) { (user, error) in
print("User logged in the firebase")
// adding a reference to our firebase database
let ref = FIRDatabase.database().referenceFromURL("https://project-12345.firebaseio.com/")
// guard for user id
guard let uid = user?.uid else {
return
}
// create a child reference - uid will let us wrap each users data in a unique user id for later reference
let usersReference = ref.child("users").child(uid)
// performing the Facebook graph request to get the user data that just logged in so we can assign this stuff to our Firebase database:
let graphRequest : FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "id, name, email"])
graphRequest.startWithCompletionHandler({ (connection, result, error) -> Void in
if ((error) != nil) {
// Process error
print("Error: \(error)")
} else {
print("fetched user: \(result)")
// Facebook users name:
let userName:NSString = result.valueForKey("name") as! NSString
self.usersName = userName
print("User Name is: \(userName)")
print("self.usersName is \(self.usersName)")
// Facebook users email:
let userEmail:NSString = result.valueForKey("email") as! NSString
self.usersEmail = userEmail
print("User Email is: \(userEmail)")
print("self.usersEmail is \(self.usersEmail)")
// Facebook users ID:
let userID:NSString = result.valueForKey("id") as! NSString
self.usersFacebookID = userID
print("Users Facebook ID is: \(userID)")
print("self.usersFacebookID is \(self.usersFacebookID)")
}
})
// set values for assignment in our Firebase database
let values = ["name": self.usersName, "email": self.usersEmail, "facebookID": self.usersFacebookID]
// update our databse by using the child database reference above called usersReference
usersReference.updateChildValues(values, withCompletionBlock: { (err, ref) in
// if there's an error in saving to our firebase database
if err != nil {
print(err)
return
}
// no error, so it means we've saved the user into our firebase database successfully
print("Save the user successfully into Firebase database")
})
}
}
})
}
更新
显然在10分钟左右之后,数据库被更新了空的Facebook数据......不知道为什么这么长时间。这是一个截图:
答案 0 :(得分:4)
Swift 3 :(最后只更改了它,节省了很多行)
func showLoginView() {
let loginManager = FBSDKLoginManager()
loginManager.logInWithReadPermissions(fbPermissions, fromViewController: self, handler: { (result:FBSDKLoginManagerLoginResult!, error:NSError!) -> Void in
if ((error) != nil) {
print("Error loggin in is \(error)")
} else if (result.isCancelled) {
print("The user cancelled loggin in")
} else {
// No error, No cancelling:
// using the FBAccessToken, we get a Firebase token
let credential = FIRFacebookAuthProvider.credentialWithAccessToken(FBSDKAccessToken.currentAccessToken().tokenString)
// using the credentials above, sign in to firebase to create a user session
FIRAuth.auth()?.signInWithCredential(credential) { (user, error) in
print("User logged in the firebase")
// adding a reference to our firebase database
let ref = FIRDatabase.database().referenceFromURL("https://project-12345.firebaseio.com/")
// guard for user id
guard let uid = user?.uid else {
return
}
// create a child reference - uid will let us wrap each users data in a unique user id for later reference
let usersReference = ref.child("users").child(uid)
// performing the Facebook graph request to get the user data that just logged in so we can assign this stuff to our Firebase database:
let graphRequest : FBSDKGraphRequest(graphPath: "/me", parameters: ["fields": "id, email, name"]).start{
(connection, result, err) in
if ((error) != nil) {
// Process error
print("Error: \(error)")
} else {
print("fetched user: \(result)")
let values: [String:AnyObject] = result as! [String : AnyObject]
// update our databse by using the child database reference above called usersReference
usersReference.updateChildValues(values, withCompletionBlock: { (err, ref) in
// if there's an error in saving to our firebase database
if err != nil {
print(err)
return
}
// no error, so it means we've saved the user into our firebase database successfully
print("Save the user successfully into Firebase database")
})
}
})
}
}
})
}
答案 1 :(得分:3)
您应该只在执行完成块ws.onmessage = (e) => {
// a message was received
let message = JSON.parse(e.data);
if (message.type === 'pause') {
currentSong.pause(); // HOW DO I ALSO CALL COMPONENT RENDER() FUNCTION?
console.log('pausing: server websocket message');
} else if (message.type === 'play') {
currentSong.setCurrentTime(message.currentTime);
currentSong.play((success) => {
if (success) {
console.log('playing: server websocket message');
} else {
console.log('playback failed due to audio decoding errors');
}
});
}
};
时更新值,因为这样您将从Facebook获取数据!
export default function(state, action) {
switch (action.type) {
case CLICK_PLAY_PAUSE_BUTTON:
let newState = cloneObject(state);
newState.isPlaying = !state.isPlaying;
if (newState.isPlaying) {
currentSong.play(success => {
// Can't figure out why this callback never calls!
if (success) {
console.log('successfully finished playing: button pressed');
} else {
console.log('playback failed due to audio decoding errors');
}
});
currentSong.getCurrentTime(seconds => {
ws.send(JSON.stringify({ type: 'play', currentTime: seconds, name: userName }));
});
} else {
currentSong.pause();
currentSong.getCurrentTime(seconds => {
ws.send(JSON.stringify({ type: 'pause', currentTime: seconds, name: userName }));
});
}
return newState;
default:
// if state is undefined return newState instead
// of boolean
return state || newState;
}
};
需要位于完成区graphRequest.startWithCompletionHandler
内。我在下面附上了它。试试!!
usersReference.updateChildValues