尝试将对象添加到Class并将信息保存到Firebase数据库

时间:2019-06-17 13:37:14

标签: swift firebase class firebase-realtime-database

我想通过我的应用程序中的视图控制器保存新对象。但是,我希望在应用程序登录时加载这些新对象。我正在使用Firebase将数据保存到数据库中,但是当应用程序再次登录时,如何保存对象并使它返回呢?我是编程新手,对于可能造成的混乱,我们深表歉意。

在此处登录应用程序后将在其中读取目标信息。

for i in 0 ... clientList.count - 1 {

screenHandle = ref?.child(organizationCode).child(clientList[i].name).observe(.value, with: { (snapshot) in
    let clientStuffLoad = snapshot.value as! [String:Any]

    if clientStuffLoad["Goal 1 Description"] != nil {
        clientList[i].goal1 = clientStuffLoad["Goal 1"] as! String
    } else {
        clientList[i].goal1 = ""
    }

从本质上讲,这是我将新成员添加到类Client的目的:

@IBAction func addingClientSaveButton(_ sender: Any) {


        var client7 = Client(name: addingClientName.text!, 
                      goal1: addingClientGoal1.text!, goal2: 
                      addingClientGoal2.text!, 
                      goal3: addingClientGoal3.text!, 
                      isSelected: false, s: 1, 
                      ind: 1, targetBehavior1 : addingClientTB1.text!, 
                      targetBehavior2 : addingClientTB2.text!, 
                      targetBehavior3 : addingClientTB3.text!, 
                      targetBehavior1Info : addingClientTB1Info.text!, 
                      targetBehavior2Info : addingClientTB2Info.text!, 
                      targetBehavior3Info : addingClientTB3Info.text!)

但是我希望对象名称读取输入的客户端名称,而不是client7

第二部分是我想要一种将其写入数据库的方法,并且能够在登录时读取它,以便可以使用类的属性并在添加新客户端时将其添加到数据库中。

1 个答案:

答案 0 :(得分:0)

这是一个非常广泛的问题,因为它涵盖了使用Firebase的许多不同方面。另外,我不知道您的数据代表什么,所以我为我挑选了一些内容来介绍使用Firebase的某些方面。

没有错误检查,但它按原样工作。我一直在评论。

Firebase没有对象;仅父级和子级节点。一切都可以视为关键:像字典一样的值对。您不能编写对象或读取对象。只有NSString,NSNumber,NSDictionary和令人恐惧的NSArray(或其Swift副本)

让我们从一个类开始-有100种方法可以做到这一点,但是我希望类负责它们的属性以及接受和展示它们

class WineClass {
    var wine_key = ""
    var name = ""
    var varietal = ""

    //this is used when creating a new wine object before storing in firebase
    init(withName: String, andVarietal: String) {
        self.name = withName
        self.varietal = andVarietal
    }

    //this is used when we are loading data from firebase to create the wineclass object
    init(withSnapshot: DataSnapshot) {
        let wineName = withSnapshot.childSnapshot(forPath: "wine_name").value as? String ?? "No Wine Name"

        let wineDict = withSnapshot.value as! [String: Any]
        let wineVarietal = wineDict["wine_varietal"] as? String ?? "No Wine Varietal"

        self.wine_key = withSnapshot.key //when we read a wine, this will be it's reference in case we want to update or delete it
        self.name = wineName
        self.varietal = wineVarietal
    }

    //this is use to create a dictionary of key:value pairs to be written to firebase
    func getWineDictForFirebase() -> [String: Any] {
        let d = [
            "wine_name": self.name,
            "wine_varietal": self.varietal
        ]

        return d
    }
}

然后,我们需要一个类var来存储WineClass的。例如,这将是tableView的数据源

var wineArray = [WineClass]() //a class var array to store my wines

然后,我将为您提供两个按钮,一个按钮填充并向Firebase写一些酒,然后另一个按钮将其读入并打印到控制台

func button0() {
    self.writeWine(withName: "Scarecrow", andVarietal: "Red Blend")
    self.writeWine(withName: "Ghost Horse", andVarietal: "Cabernet Sauvignon")
    self.writeWine(withName: "Screaming Eagle", andVarietal: "Cabernet Sauvignon, Merlot, Cabernet Franc")
}

func button1() {
    self.readWines()
}

然后该函数接受每种酒的某些字符串作为属性并将其写入Firebase

func writeWine(withName: String, andVarietal: String) {
   let newWine = WineClass(withName: withName, andVarietal: andVarietal) //create a new wine object

   let wineListRef = self.ref.child("wine_list") //get a reference to my firebase wine_list
   let thisWineRef = wineListRef.childByAutoId() //a new node for this wine
   let d = newWine.getWineDictForFirebase() //get the wine properties as a dictionary
   thisWineRef.setValue(d) //save it in firebase
}

最后是一个读取这些葡萄酒并在控制台中打印其属性的函数

func readWines() {
   let wineRef = self.ref.child("wine_list")
   wineRef.observeSingleEvent(of: .value, with: { snapshot in //we are reading in the entire wine node which will contain many child nodes
       let allWines = snapshot.children.allObjects as! [DataSnapshot] //cast each child node as a DataSnapshot & store in array
       for wineSnap in allWines { //iterate over each child node in the array
           let wine = WineClass(withSnapshot: wineSnap) //create a new wine, ensuring we also keep track of it's key
           self.wineArray.append(wine) //add to the array
       }

       for wine in self.wineArray  {
           print(wine.wine_key, wine.name, wine.varietal)
       }
   })
}

最后,当单击button0时,我们的Firebase看起来像这样

wine_list
   -LhbjhkEC8o9TUISCjdw
      wine_name: "Scarecrow"
      wine_varietal: "Red Blend"
   -LhbjhkEC8o9TUISCjdx
      wine_name: "Ghost Horse"
      wine_varietal: "Cabernet Sauvignon"
   -LhbjhkEC8o9TUISCjdy
      wine_name: "Screaming Eagle"
      wine_varietal: "Cabernet Sauvignon, Merlot, Cabernet Franc"

然后单击button1时的输出

-LhbjhkEC8o9TUISCjdw Scarecrow Red Blend
-LhbjhkEC8o9TUISCjdx Ghost Horse Cabernet Sauvignon
-LhbjhkEC8o9TUISCjdy Screaming Eagle Cabernet Sauvignon, Merlot, Cabernet Franc

请注意,self.ref是对我的Firebase 根节点的引用,您将需要引用您的 Firebase。