swift如何向火力点数据库添加模型数据对象

标签: ios Swift
发布时间: 2017/3/6 23:38:01
注意事项: 本文中文内容可能为机器翻译,如要查看英文原文请点击上面连接.

我有两个问题︰

  1. 我知道如何向火力点使用简单的键 / 值对添加的常规对象,但如何将添加一个用户对象吗?

  2. 我应将用户帐户对象中我确信不到关于 UserAcct 的第二个 init 方法。我应该使用 init(snapshot: FIRDataSnapshot) {} 向火力点添加或应我只是坚持定期 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])    
        }
    })
}

解决方法 1:

这是我用的方法。我解释了一切在上面的代码注释。也许它会帮助别人。

我的用户模型对象。那里是没有需要添加 init 方法。

import Foundation
import UIKit

class UserAccount{
     var userID: String?
     var email: String?
     var creationDateInSecs: NSNumber?
}

我班签约用户︰

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)")
   }

      //This constant holds the uid. Your FIRAuth uid is now the value from user!uid above
      let currentUserID = FIRAuth.auth()?.currentUser?.uid

      //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 usersRef = self.dbRef.child("users")
      let userIDRef = usersRef.child(currentUserID!)
      let userAccountRef = userIDRef.child("userAccount")

      //This is the UserAcount Model object. You instantiate it then you set the properties in the object to the values such as the uid, email address, and timestamp in secs
      let userAccount = UserAccount()
      userAccount.userID = currentUserID!
      userAccount.email = self.emailTextField.text!
      userAccount.creationDateInSecs = self.timeStamp!

      //Here you initialize an empty dictionary to hold the keys and values you want uploaded to your database
      let userAccountDict = [String:AnyObject]()

      //Here you can use a dictionary method to update the keys and matching values. The values are the ones from your UserAccount model's properties and the keys are what I decided I wanted them to be named in FirebaseDatabase. You use these keys to extract the values
      userAccountDict.updateValue(userAccount.userID!, forKey: "userIDKey")
      userAccountDict.updateValue(userAccount.email!, forKey: "emailKey")
      userAccountDict.updateValue(userAccount.creationDateInSecs!, forKey: "acctCreationDateKey")

      //Here you upload your dictionary with the keys and values you set above. Your database will hold these key/value pairs under the "userAccount" node. userAccountRef (you set it above) is the constant that has that node value
      userAccountRef.updateChildValues(userAccountDict, withCompletionBlock: {

                (error, user) in

                if error != nil{
                    print("Account-Database Error: \(error?.localizedDescription)\n")
                }

        })
     })
   }
  }

这是一个小小的关闭主题,但如果你想要秒中的时间戳转换为可读性更好的格式您可以使用此函数显示月-日-年小时分钟上午 / 下午 FYI 秒中的时间戳是可取和将会更容易,如果你需要到后来的排序方式。

//Custom Date
    func convertedTimeStampSecsToCurrentDate() -> String?{

        //Current Timestamp in Seconds
        let timeStampInSeconds:NSNumber? = Int(NSDate().timeIntervalSince1970)

        var currentDate: String?

        if let seconds = timeStampInSeconds{
            let currentTimeStamp = NSDate(timeIntervalSince1970: seconds.doubleValue)
            let dateFormatter = NSDateFormatter()
            dateFormatter.dateFormat = "MM-dd-yyyy HH:mm a"
            let formattedDate = dateFormatter.stringFromDate(currentTimeStamp)
            currentDate = formattedDate
        }
        return currentDate!
    }

如果你这样做你可以摆脱时间戳属性在班上名列前茅。你还要更改您应将用户帐户属性 'creationDateInSecs' 是字符串类型。

示例

class UserAccount{
     var userID: String?
     var email: String?
     var creationDate: String?
}

在 CreateAccountController,你可以设置使用 convertedTimeStampSecsToCurrentDate() 函数,属性的值。这是 FIRAuth.auth() 里面吗?。createUserWithEmail 方法之前设置字典键值。请确保您添加的 convertedTimeStampSecsToCurrentDate() 函数的 CreateAccountController 类,所以您就可以使用它。

let userAccount = UserAccount()
userAccount.userID = currentUserID!
userAccount.email = self.emailTextField.text!
userAccount.creationDate = self.convertedTimeStampSecsToCurrentDate()

希望这有助于一个人 !

赞助商