【问题标题】:How to add model data objects to Firebase database如何将模型数据对象添加到 Firebase 数据库
【发布时间】:2016-11-19 14:55:27
【问题描述】:

我有两个问题:

  1. 我知道如何使用简单的键值对向 Firebase 添加常规对象,但如何添加用户对象?

  2. 在我的 UserAccount 对象中,我不确定 UserAcct 的第二个 init 方法。我应该使用 init(snapshot: FIRDataSnapshot){} 添加到 Firebase 还是应该坚持使用常规的 init 方法?

我的用户模型对象:

import Foundation
import UIKit
import Firebase
import FirebaseDatabase

    class UserAccount{

        var userID: String
        var email: String
        var creationDate: String

        init(userID: String, email: String, creationDate: String){

            self.userID = userID
            self.email = email
            self.creationDate = creationDate
        }//end init

        //Is this second init necessary?
        init(snapshot: FIRDataSnapshot) {
            userID = snapshot.value!["userID"] as! String
            email = snapshot.value!["email"] as! String
            creationDate = snapshot.value!["creationDate"] as! String
        }

    }//END class

我的用户注册课程:

    import UIKit
        import Firebase
        import FirebaseAuth
        import FirebaseDatabase

        class CreateAccountController: UIViewController{

        @IBOutlet weak var emailTextField: UITextField!
        @IBOutlet weak var passwordTextField: UITextField!


        var dbRef: FIRDatabaseReference!

        //Array to hold users
        var userAcct = [UserAccount]()


        override func viewDidLoad() {
                    super.viewDidLoad()

                    //Firebase Ref
                    self.dbRef = FIRDatabase.database().reference()
                }

        //Button to sign the user up
        @IBAction func signUpButtonPressed(sender: UIButton) {


        FIRAuth.auth()?.createUserWithEmail(emailTextField.text!, password: passwordTextField.text!, completion: {

                        (user, error) in

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

        let emailAddress = self.emailTextField.text!
        let currentUserID: String = (FIRAuth.auth()?.currentUser?.uid)!
        let accountCreationDate = FIRServerValue.timestamp()

        self.userAcct =[UserAccount(userID: currentUserID, email: emailAddress, creationDate: accountCreationDate)]


        self.dbRef.child("Users").child("UserID: \(currentUserID)").child("Account-Creation-Date").setValue([\\How to add my self.userAcct model object in here? Should I add it to an array])    
        }
    })
}

【问题讨论】:

    标签: ios swift firebase firebase-realtime-database


    【解决方案1】:

    我建议你创建一个像这样的协议:

    protocol DictionaryConvertible {
        init?(dict:[String:AnyObject])
        var dict:[String:AnyObject] { get }
    }
    

    请注意,这是使用可选的初始化程序,这意味着它可能会失败并返回 nil。我用它来确保您需要的字典中的所有键值对都确实存在,否则返回 nil。现在您可以像这样为您的 UserAccount 类添加一致性:

    class UserAccount: DictionaryConvertible {
    
        var userID: String
        var email: String
        var creationDate: String
    
        init(userID: String, email: String, creationDate: String){
            self.userID = userID
            self.email = email
            self.creationDate = creationDate
        }
    
        // DictionaryConvertible protocol methods
        required convenience init?(dict: [String:AnyObject]) {
            guard let userID = dict["userID"] as? String, email = dict["email"] as? String, creationDate = dict["creationDate"] as? String else {
                return nil
            }
            self.init(userID: userID, email: email, creationDate: creationDate)
        }
        var dict:[String:AnyObject] {
            return [
                "userID": userID,
                "email": email,
                "creationDate": creationDate
            ]
        }
    }
    

    注意:我使用您已经制作的初始化程序来摆脱样板代码。要与 Firebase 交互,只需像这样初始化您的 UserAccount:

    let user:UserAccount? = UserAccount(dict: snapshot?.value as! [String:Anyobject])
    

    要回答您的第一个问题,您可以像这样将对象写入 firebase:

    ref.child("Users").child(user!.userID).setValue(user!.dict)
    

    您不能只将任何类型的对象写入 firebase(仅 NSNumber(包括 BOOL)、NSDictionary、NSArray、NSString、nil / NSNull 来删除数据),因此您必须将您的用户对象“转换”为字典。

    这种方法的优点在于它很灵活,因此您可以通过添加对协议的一致性来使用任何数据对象(当您使用结构而不是类时尤其容易,因为您可以使用扩展来添加对协议的一致性)。您甚至可以将它与任何与字典一起使用的数据库一起使用,而无需进行太多更改。此外,您应该确保以安全的方式处理所有这些选项,并避免使用那些“!”尽可能。

    【讨论】:

    • 感谢您的帮助。我还没有尝试过,但信息应该足以让我去我需要去的地方
    • @dennism,关于您创建的字典项目的问题。那只是firebase中的一个平面对象,如果节点有子节点怎么办,字典对象会如何变化?!我正在尝试"poster/username": userName.... 这应该表示用户名信息位于“海报”子节点下。
    【解决方案2】:

    这是我使用的方法。我在代码上方的 cmets 中解释了所有内容。

    最终结果是你创建了一个字典:

    let dict = [String:Any]()
    

    然后您使用字典的 updateValue 方法更新键值对:

    dict.updateValue(someValue, forKey: “someKey”)
    

    然后你最终将该字典上传到数据库:

    let userAccountRef = self.dbRef.child("users").child(theUsersID).child(“userAccount”)
    
    userAccountRef.updateChildValues(dict)
    

    我的用户注册课程:

    import UIKit
    import Firebase
    import FirebaseAuth
    import FirebaseDatabase
    
    class CreateAccountController: UIViewController{
    
    @IBOutlet weak var emailTextField: UITextField!
    @IBOutlet weak var passwordTextField: UITextField!
    
    //Your firebase reference
    var dbRef: FIRDatabaseReference!
    
    //Current Timestamp in Seconds. You can convert the value later on
    let timeStamp:NSNumber? = Int(NSDate().timeIntervalSince1970)
    
    override func viewDidLoad() {
          super.viewDidLoad()
         //Firebase Reference to our database
         self.dbRef = FIRDatabase.database().reference()
    }
    
    //Button to sign the user up
    @IBAction func signUpButtonPressed(sender: UIButton) {
    
       FIRAuth.auth()?.createUserWithEmail(emailTextField.text!, password: passwordTextField.text!, completion: {
    
            //This is where your uid is created. You can access it by using user!uid. Be sure to unwrap it.
            (user, error) in
            print("my userID is \(user.uid)")
    
          if error != nil{
              print("Account Creation Error: \(error?.localizedDescription)")
              return
          }
    
          //This constant holds the uid. It comes from the (user, error). The user argument has a uid string property
          let currentUserID = user!.uid // which is the same as FIRAuth.auth()?.currentUser?.uid
    
          //Here you initialize an empty dictionary to hold the keys and values you want uploaded to your database
          let dict = [String:Any]()
    
          //use the dictionary’s updateValue() method to update the values and matching keys
          dict.updateValue(currentUserID, forKey: "userIDKey")
          dict.updateValue(self.emailTextField.text!, forKey: "emailKey")
          dict.updateValue(self.timeStamp!, forKey: "acctCreationDateKey")
    
          //This gives you reference to your database, then to a child node named "users", then another node using the uid, and finally to another node named "userAccount". This final node is where you will keep your dictionary values for your database.
          let userAccountRef = self.dbRef.child("users").child(currentUserID).child(“userAccount”)
    
          //Here you upload your dictionary to the userAccountRef with the dictionary key/values you set above using the dict’s updateValue() method
          userAccountRef.updateChildValues(dict)
       })
    }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-10-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-09
      • 1970-01-01
      相关资源
      最近更新 更多