如何将数据添加到firebase数据库中的特定用途参考?

时间:2017-08-26 00:19:22

标签: ios swift firebase firebase-realtime-database

我当前的iOS要求用户注册并登录,一旦用户登录,数据就会通过他们user.uid及他们注册的电子邮件地址在数据库中显示。用户登录后,我希望用户能够在其特定的user.uid节点上存储数据。例如,如果"用户A"登录并输入某种类型的数据,我希望数据保存在该用户下面(因此每个用户应该包含自己的数据集,不应该访问或修改除此之外的任何其他用户数据)。所以我的问题是,跟踪登录用户或访问登录用户以便在以后的视图控制器中存储未来引用的最佳方法是什么?它是一个食品配送应用程序,因此一旦用户登录,我希望将来输入的所有数据都保存在数据库中的该用户下。

登录控制器代码:

 import UIKit
 import FirebaseDatabase
 import FirebaseAuth

 class LogInController: UIViewController {

var ref: DatabaseReference!


@IBOutlet weak var emailField: UITextField!
@IBOutlet weak var passwordField: UITextField!


func placeholders() {
    emailField.placeholder = "Enter Email"
    passwordField.placeholder = "Enter Password"
}






@IBAction func loginButton(_ sender: AnyObject) {

    Auth.auth().signIn(withEmail: emailField.text!, password: passwordField.text!, completion: { (user, error) in




        let userID: String = (user?.uid)!
        let userEmail: String = self.emailField.text!

        self.ref.child("Users/\(userID)").setValue(userEmail)




        if error != nil {
            print(error?.localizedDescription as Any)
        }

        else {
            print("User logged in with UserID of: " + (user?.uid)!)
        }
        })
    performSegue(withIdentifier: "signedIn", sender: self)


}



@IBAction func signoutButton(_ sender: Any) {
    print("User has logged out...")
   try!  Auth.auth().signOut()
}



@IBAction func registerButton(_ sender: AnyObject) {

    Auth.auth().createUser(withEmail: emailField.text!, password: passwordField.text!, completion: { (user, error) in

        if error != nil {
            print(error?.localizedDescription as Any)
            return
        }

            print("User created with UserId of: " + (user?.uid)!)


    })
}



override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let flavorsVC = segue.destination as? FlavorsController {
        flavorsVC.ref = ref
        let userEmail = emailField.text
        flavorsVC.email = userEmail!

    }
}







override func viewDidLoad() {
    super.viewDidLoad()


    placeholders()
    ref = Database.database().reference()

}

再次,一旦用户登录,我希望输入的所有数据都保存在以下视图控制器上的登录用户下。例如,在下一个视图控制器中,我有一个变量bookieAmount,我怎样才能将我的代码修改为每个登录用户都有一个单独的节点,其中个人bookieAmount可以保存到哪个节点?到目前为止,当我尝试实现这样的功能时,它只是替换了之前的参考,并没有像我想要的那样为特定用户创建新的。

下一个视图控制器的代码:

  class FlavorsController: UIViewController, UITableViewDelegate, UITableViewDataSource {

var bookieFlavors = ["Chocolate Chip", "Sugar w/o icing", "Sugar w/ icing", "Peanut Butter", "Honey", "Shortbread", "Ginger", "Double Chocolate", "Macadamie Nut", "Oatmeal Raisin", "Snickerdoodle"]
var amount = [Int]()
var bookieTotal = Int()
var ref: DatabaseReference!
var flavorRef: DatabaseReference!
var email = String()





override func viewDidLoad() {
    super.viewDidLoad()
    for _ in self.bookieFlavors {
        self.amount.append(0)
    }
    flavorTable.delegate = self
    flavorTable.dataSource = self

    //database references
    ref = Database.database().reference()
    flavorRef = Database.database().reference()



}

func emptyAmount(_ sender: UIButton) {
    print("Button Held, Amount Emptied")
    self.amount[sender.tag] = self.amount[sender.tag] - (self.amount[sender.tag] + 1)
    let cell = self.flavorTable.cellForRow(at: IndexPath(row: sender.tag, section: 0)) as? FlavorTableCell
    cell?.bookieAmount.text = "= \(self.amount[sender.tag])"

}


@IBAction func bookieButton(_ sender: UIButton) {

    self.amount[sender.tag] = self.amount[sender.tag] + 1
    let cell = self.flavorTable.cellForRow(at: IndexPath(row: sender.tag, section: 0)) as? FlavorTableCell
    cell?.bookieAmount.text = "= \(self.amount[sender.tag])"
   // print(amount[sender.tag])

    self.bookieTotal = amount.reduce(0, +)
    print(bookieTotal)
}




@IBOutlet weak var flavorTable: UITableView!


func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int    
{
    return bookieFlavors.count

}

func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! FlavorTableCell


    //flavor label configuration
    cell.flavorLabel.text = bookieFlavors[indexPath.row]

    //amount configuration
    cell.bookieAmount.text = "= \(self.amount[indexPath.row])"
    cell.bookieButton.tag = indexPath.row
    cell.bookieButton.addTarget(self, action: #selector(bookieButton(_:)), for: .touchUpInside)
    cell.bookieButton.addTarget(self, action: #selector(emptyAmount(_:)), for: .touchDownRepeat)

    return cell

}

@IBAction func registerBookieAmount(_ sender: Any) {
    print(bookieTotal)

    let amount: Int = bookieTotal
    let user = Auth.auth().currentUser

    if ((user) != nil) {


    }

}

1 个答案:

答案 0 :(得分:1)

您可以做的是向Firebase服务器发出请求,以查看用户是否仍然使用此代码登录

if Auth.auth().currentUser != nil {
  // User is signed in.
  let ref = Database.database().reference()
  ref.child("users").child(user.uid).child("orders").setValue(["order": orderNumber])
} else {
  // No user is signed in.

}