Ben Ben - 1 month ago 24
Swift Question

Convert Firebase Dictionary Data to Array (Swift)

This may be a simple answer, so apologies in advance, but I'm stuck because I'm still getting head wrapped around how Firebase works. I want to query a Firebase Database based on unix date data that is saved there and then take the related "Unique ID" data and put it into an array.

The data in Firebase looks like this:

posts
node_0
Unix Date: Int
Unique ID Event Number: Int
node_1
Unix Date: Int
Unique ID Event Number: Int
node_2
Unix Date: Int
Unique ID Event Number: Int


What I have so far is as follows. The query part seems to be working as expected. Where I'm struggling is how to put the "Unique ID Event Number" data into an array. This is the approach that seemed closest to success, which is based on this post, but I get an error that child has no member of "value".

// Log user in
if let user = FIRAuth.auth()?.currentUser {

// values for vars sevenDaysAgo and oneDayAgo set here

...

let uid = user.uid

//Query Database to get the places searched by the user between one and seven days ago.
let historyRef = self.ref.child("historyForFeedbackLoop/\(uid)")
historyRef.queryOrdered(byChild: "Unix Date").queryStarting(atValue: sevenDaysAgo).queryEnding(atValue: oneDayAgo).observeSingleEvent(of: .value, with: { snapshot in

if (snapshot.value is NSNull) {
print("error")
}
else {

for child in snapshot.children {

if let uniqueID = child.value["Unique ID Event Number"] as? Int {

arrayOfUserSearchHistoryIDs.append(uniqueID)
}
}
}
})
}
else {
print("auth error")
}


Any ideas are greatly appreciated!

Answer

Try using this:-

   historyRef.queryOrdered(byChild: "Unix Date").queryStarting(atValue: sevenDaysAgo).queryEnding(atValue: oneDayAgo).observeSingleEvent(of: .value, with: { snapshot in

       if let snapDict = snapshot.value as? [String:AnyObject]{

               for each in snapDict{

                       let unID = each.value["Unique ID Event Number"] as! Int   
                       arrayOfUserSearchHistoryIDs.append(unID)  
                    }

              }else{
               print("SnapDict is null")
          }

        })
Comments