如何使用Firebase创建用户名?

时间:2017-03-19 11:47:50

标签: ios swift firebase firebase-authentication

我仍然不熟悉使用Xcode和使用Firebase进行快速编码。我已经能够使用Firebase身份验证创建注册和登录页面。我一直在想如何让人们创建自定义的唯一用户名。我一直在网上搜索一段时间,但我找不到多少。

我想了解如何在我的应用中实现用户名,以便用户可以创建唯一的用户名并拥有自己的个人资料。

2 个答案:

答案 0 :(得分:1)

在Firebase Auth中创建用户后,执行以下操作:

let newUser = UserItem(uid: < Value >, email: < Value >, login: < Value >, createdDate: < Value >)

// Create a child path with a key set to the uid underneath the "users" node
let refToMainDB = FIRDatabase.database().reference(withPath: "< PathToMainDB >")
refToMainDB.child("users").child(< uid >).setValue(newUser.toAnyObject()

例如我的UserItem结构:

import Foundation
import FirebaseAuth
import FirebaseDatabase

struct UserItem {
let uid: String

let email: String
let login: String
let bioDescription: String
let nameAndSename: String
let createdDate: String

let ref: FIRDatabaseReference?

init(uid: String, email: String, login: String, bioDescription: String = "", nameAndSename: String = "", createdDate: String) {
    self.uid = uid

    self.email = email
    self.login = login
    self.bioDescription = bioDescription
    self.nameAndSename = nameAndSename
    self.createdDate = createdDate

    self.ref = nil
}

init(snapshot: FIRDataSnapshot) {
    uid = snapshot.key

    let snapshotValue = snapshot.value as! [String: AnyObject]
    email = snapshotValue["email"] as! String
    login = snapshotValue["login"] as! String
    bioDescription = snapshotValue["bioDescription"] as! String
    nameAndSename = snapshotValue["nameAndSename"] as! String
    createdDate = snapshotValue["createdDate"] as! String

    ref = snapshot.ref
}

func toAnyObject() -> Any {
    return [
        "uid": uid,
        "email": email,
        "login": login,
        "bioDescription": bioDescription,
        "nameAndSename": nameAndSename,
        "createdDate": createdDate
    ]
}
}

您可以查看我的here代码示例 希望它有所帮助

答案 1 :(得分:0)

除了我的评论。

let currentUserId = FIRAuth.auth()?.currentUser?.uid
let currentUserRef = FIRDatabase.database().reference(withPath: "MainDataBase/users").child(currentUserId!) // MainDataBase/users - is part from you database

currentUserRef.observeSingleEvent(of: .value, with: { snapshot in
        self.userInfo = UserItem(snapshot: snapshot)
        self.label.text = "Welcome " + (self.userInfo.login)!  // for example it will show login
    })
祝你好运

修改 有这样的事情会更好:

var userInfo: UserItem! {
    didSet {
        self.label.text = "Welcome " + (self.userInfo.login)!  // for example it will show login
        // other actions
    }