如何通过传递Firebase参考来跟踪用户?

时间:2017-08-25 19:55:40

标签: ios swift firebase firebase-realtime-database firebase-authentication

所以我正在构建一个iOS应用程序,它要求用户注册并登录。登录后,登录视图控制器会切换到用户输入数据的表视图控制器。在用户确认他们输入的数据信息之后,它然后转到交付信息视图控制器,在那里他们输入送货地址信息。我的问题是如何才能将用户输入的数据和他们输入的送货地址信息保留在该特定用户的引用位置?这样,如果另一个用户登录,他们的数据量和送货地址信息将存储在他们自己的节点下并与其他任何用户分开?想象一下,像任何食品配送应用程序一样,我很想知道他们如何跟踪每个用户的订单,送货地址等附加到该特定用户?现在,每当我尝试使用不同的用户创建新的引用时,它都会替换旧的引用,即使它是由不同的用户存储的。

 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").childByAutoId().setValue(userEmail + " " + userID)




        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()

}

查看控制器我尝试将数据保存在:

import UIKit
import FirebaseAuth
import Firebase
import FirebaseDatabase

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 :(得分:2)

现在,如果不了解您的数据结构,这有点困难,但看起来每次用户登录时,都会使用此代码为他们创建一个新节点:

self.ref.child("Users").childByAutoId().setValue(userEmail + " " + userID)

不使用childByAutoId()创建唯一的推送ID,而是使userID成为关键:

self.ref.child("Users/\(userID)").setValue(["email": userEmail])

然后,您可以侦听ref.child("Users/\(userID)")的值以获取用户的已保存数据。您还可以将任何数据写入同一路径,例如您提到的送货地址。

顺便说一句,我建议在self.ref.child("Users/\(userID)").setValue(["email": userEmail])内调用createUser(withEmail: email, password: password),因为每次用户登录时都不需要重写此节点。