Ler Ws Ler Ws - 1 month ago 16
iOS Question

How do I read a Firebase Snapshot and store a particular key-value pair in a universal array?

How do I extract the URL of every snapshot result found and append it to an array in Swift?

Snap (palettes) {
"-KSoMzY6OYPyXnOPeZMb" = {
0 = "#000000";
1 = "#423831";
2 = "#2C2923";
3 = "#424131";
4 = "#35382A";
URL = test;
};
"-KSoN-LT8I--3m-BBbfw" = {
0 = "#000000";
1 = "#F6DBC5";
2 = "#E0D6BE";
3 = "#F6F6C5";
4 = "#E1ECBD";
URL = test2;
};


Here's my returning JSON structure for example after calling:

databaseRef.child("palettes").queryOrdered(byChild: "0").queryEqual(toValue: text).observeSingleEvent(of: .value, with: { (snapshot) in
print (snapshot)
})


How do I extract the URL of the multiple result snapshot and then append it to an array in Swift so the end result becomes
array = [test, test2]
?

Thanks.

Edit

Here's my JSON tree:

{
"palettes" : {
"-KSoMzY6OYPyXnOPeZMb" : {
"0" : "#000000",
"1" : "#423831",
"2" : "#2C2923",
"3" : "#424131",
"4" : "#35382A",
"URL" : "test"
},
"-KSoN-LT8I--3m-BBbfw" : {
"0" : "#000000",
"1" : "#F6DBC5",
"2" : "#E0D6BE",
"3" : "#F6F6C5",
"4" : "#E1ECBD",
"URL" : "test2"
},
"-KSoN-e0huiOxyj0jadl" : {
"0" : "#F1CBC1",
"1" : "#FBE1C9",
"2" : "#E5DCC2",
"3" : "#FBFBC9",
"4" : "#000000",
"URL" : "test3"
},
"-KSqFcPjjtRkRDbzH-lc" : {
"0" : "#27643A",
"1" : "#2B6E52",
"2" : "#000000",
"3" : "#2B676E",
"4" : "#274E64",
"URL" : "test4"
}
}
}

Answer

Try this:-

var arrayVar = [String]()

FIRDatabase.database().reference().child("palletes").observeSingleEvent(of: .value, with: {(snap) in

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

            for each in snapDict as [String:AnyObject]{

                let _URL = each.value["URL"] as! String
                arrayVar.append(_URL)

            }
        }
    })
Comments