1

I am trying to pull a list of data from my Firebase Database. Below is my code. Both functions are called in my viewDidLoad(); however, the print(theLikeArray) is returning empty brackets even though my database is fully populated.

Below is the code I am currently using. The first function is used to retrieve all the information from the database while the second is used to populate the database. The second function is called prior to the first.

func retriveDiscounts() {
    let likesDB = Database.database().reference().child("Discounts")
    likesDB.observe(.childAdded) { (snapshot) in
        let snapshotValue = snapshot.value as! Dictionary<String , String>
        let businessID = Int(snapshotValue["BusinessID"]!)
        let businessName = snapshotValue["businessName"]!
        let DateNumber = Int(snapshotValue["DateNumber"]!)
        let theDeal = snapshotValue["theDeal"]!
        let phoneNumber = snapshotValue["PhoneNumberText"]!
        let imageName = snapshotValue["ImageName"]!
        let dateText = snapshotValue["DateText"]!
        let phoneNumberInteger = Int(snapshotValue["phoneNumberInteger"]!)
        let companyLogo = snapshotValue["companyLogo"]!
        let r1 = Int(snapshotValue["r1"]!)
        let r2 = Int(snapshotValue["r2"]!)
        let r3 = Int(snapshotValue["r3"]!)
        let classification = snapshotValue["classification"]!
        let allTheLikes = likeclass()
        allTheLikes.discountID = businessID!
        allTheLikes.businessName = businessName
        allTheLikes.dateApplied = DateNumber!
        allTheLikes.theDeal = theDeal
        allTheLikes.phoneNumber = phoneNumber
        allTheLikes.imageName = imageName
        allTheLikes.dateText = dateText
        allTheLikes.numberNumber = phoneNumberInteger!
        allTheLikes.companylogo = companyLogo
        allTheLikes.r1 = r1!
        allTheLikes.r2 = r2!
        allTheLikes.r3 = r3!
        allTheLikes.classification = classification
        self.theLikeArray.append(allTheLikes)
    }
    print(theLikeArray)
}



func updateLikeDatabase(){
    for i in 0...allDiscounts.list.count-1{
        let likesDB = Database.database().reference().child("Discounts")
        let likeDictionary = ["BusinessID": "\(i)","businessName":"\(allDiscounts.list[i].businessName)","DateNumber": "\(allDiscounts.list[i].dateApplied)","theDeal": "\(allDiscounts.list[i].theDeal)" ,"PhoneNumberText": "\(allDiscounts.list[i].phoneNumber)","ImageName": "\(allDiscounts.list[i].imageName)","DateText": "\(allDiscounts.list[i].dateText)" ,"phoneNumberInteger": "\(allDiscounts.list[i].numberNumber)","companyLogo": "\(allDiscounts.list[i].companylogo)","r1": "\(allDiscounts.list[i].r1)" ,"r2": "\(allDiscounts.list[i].r2)","r3": "\(allDiscounts.list[i].r3)","classification": "\(allDiscounts.list[i].classification)"] as [String : String]
        likesDB.child("\(allDiscounts.list[i].businessName)").setValue(likeDictionary) {
            (error, reference) in
            if error != nil{
                let alert = UIAlertController(title: "Error", message: "There was an error registering your like. Reconnect online and try again", preferredStyle: .alert)
                let okAction = UIAlertAction(title: "Ok", style: .default, handler: nil)
                alert.addAction(okAction)
                self.present(alert,animated: true)
                //                    self.showerror()
            }
            else{
                print("Message Saved Successfully")
            }
        }
        }
    }
Hasta Dhana
  • 4,699
  • 7
  • 17
  • 26
  • Did you check for firebase rules? Maybe your requests aren’t reaching firebase. – excitedmicrobe Sep 22 '19 at 21:44
  • @excitedmicrobe yes, the rules for read and write are both set to true – asdfnvkewn2oin Sep 22 '19 at 22:25
  • Please edit your question to include a snippet of the JSON at `Discounts` (as text, no screenshots). You can get this by clicking the "Export JSON" link in the overflow menu (⠇) on your [Firebase Database console](https://console.firebase.google.com/project/_/database/data). – Frank van Puffelen Sep 23 '19 at 05:58

1 Answers1

1

The data may have to be downloaded from the Firebase servers. Since this may take some time, that data is loaded asynchronously. Instead of blocking your main code (and making your app unresponsive), Firebase allows your main code to continue, and calls your completion handler when the data is available.

All this means is that any code that needs the data from the database must be inside the completion handler.

So in your case something like:

let likesDB = Database.database().reference().child("Discounts")
likesDB.observe(.childAdded) { (snapshot) in
    let snapshotValue = snapshot.value as! Dictionary<String , String>
    let businessID = Int(snapshotValue["BusinessID"]!)
    let businessName = snapshotValue["businessName"]!
    let DateNumber = Int(snapshotValue["DateNumber"]!)
    let theDeal = snapshotValue["theDeal"]!
    let phoneNumber = snapshotValue["PhoneNumberText"]!
    let imageName = snapshotValue["ImageName"]!
    let dateText = snapshotValue["DateText"]!
    let phoneNumberInteger = Int(snapshotValue["phoneNumberInteger"]!)
    let companyLogo = snapshotValue["companyLogo"]!
    let r1 = Int(snapshotValue["r1"]!)
    let r2 = Int(snapshotValue["r2"]!)
    let r3 = Int(snapshotValue["r3"]!)
    let classification = snapshotValue["classification"]!
    let allTheLikes = likeclass()
    allTheLikes.discountID = businessID!
    allTheLikes.businessName = businessName
    allTheLikes.dateApplied = DateNumber!
    allTheLikes.theDeal = theDeal
    allTheLikes.phoneNumber = phoneNumber
    allTheLikes.imageName = imageName
    allTheLikes.dateText = dateText
    allTheLikes.numberNumber = phoneNumberInteger!
    allTheLikes.companylogo = companyLogo
    allTheLikes.r1 = r1!
    allTheLikes.r2 = r2!
    allTheLikes.r3 = r3!
    allTheLikes.classification = classification
    self.theLikeArray.append(allTheLikes)

    print(theLikeArray)
}

Note that this is an incredibly common source of confusion, so I highly recommend that you read some other questions on the topic:

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • This was true, however, whenever i tried to index the Array in a later function (I was indexing at the first position), it would return an error saying that the index was out of range. – asdfnvkewn2oin Sep 28 '19 at 00:44
  • 1
    It sounds like you have a new problem then. I'd recommend opening a new question, with the [minimal, complete/standalone code that anyone can run to reproduce the problem](http://stackoverflow.com/help/mcve). – Frank van Puffelen Sep 28 '19 at 06:36