I am a beginner to Swift 3 (using iOS 8.3). I have been trying to figure out a way to separate the data but got no luck. Basically, I am able to extract the following data from Firebase:
{
Database = {
Kelvin = {
Institution = xxx;
"Years of Experience" = "2.5";
location = London;
};
Sophia = {
Institution = xxxx;
"Years of Experience" = 3;
location = London;
};
};
Users = {
SOOlIFsjn3839jcmlBbVEnSRH3 = {
email = "testing@gmail.com";
password = 1234567;
};
};
}
But now I want to separate the data so that it will show something like this:
var ref: FIRDatabaseReference!
ref = FIRDatabase.database().reference()
ref.observe(FIRDataEventType.value, with: { (snapshot) in
if let mydata = snapshot.value as? NSDictionary {
print(mydata)
if let namedata = mydata["Database"] as? NSArray {
print(namedata[0]) //Prints Kelvin
print(namedata[1]) //Prints Sofia
}
However, Swift doesn't allow me to do so, it tells me I cannot convert a type of NSDictionary to NSArray. Any ideas? Very much appreciated.
READ/RETRIVING DATA FROM FIREBASE DATABASE to NSDICTIONARY
Read Data Every time it changes
You can use the FIRDataEventTypeValue event to read the data at a given path, as it exists at the time of the event. This method is triggered once when the listener is attached and again every time the data, including any children, changes. The event callback is passed a snapshot containing all data at that location, including child data. If there is no data, the value of the snapshot returned is nil.
Read Data Once
This is useful for data that only needs to be loaded once and isn't expected to change frequently or require active listening. For instance, the blogging app in the previous examples uses this method to load a user's profile when they begin authoring a new post.
Firebase collections are key-value pair. For each key of the JSON, you can find the corresponding value.
So you'll need to convert to an
NSDictionary
of String, Object. The keys in that dictionary will beKelvin
andSophia
. The value for each is the value under the corresponding key.