How to loop through Firebase childByAutoId in objective c - ios

I need to loop through childByAutoId to add posts in array. So how can I access to price, title, text strings to load that data in my table?
Here is my base structure:
I read data from base in posts
[[_ref child:#"posts"]
observeEventType:FIRDataEventTypeValue
withBlock:^(FIRDataSnapshot *snapshot) {
[self.postData removeAllObjects];
// Loop over children
NSEnumerator *children = [snapshot children];
FIRDataSnapshot *child;
while (child = [children nextObject]) {
NSLog(#"child: %#", child);
[self.postData addObject:child];
}
NSLog(#"postData: %#", self.postData);
[self.postCollectionView reloadData];
}];
Here is my log:
2018-09-24 16:59:03.788023+0300 App[4904:1202383] child: Snap (-LNAfBgHiac83feC6Wm1) {
price = 3747;
text = Jfjfjf;
title = Jfjfjf;
}
2018-09-24 16:59:03.788125+0300 App[4904:1202383] child: Snap (-LNAfY-W7OZMA4Jm7TQN) {
price = 3764647;
text = Kgkgkg;
title = Blnckckc;
}
2018-09-24 16:59:03.788176+0300 App[4904:1202383] child: Snap (-LNArUfHbIV3y_hgACLr) {
title = Kgjggkkgnnc;
}
2018-09-24 16:59:03.788312+0300 App[4904:1202383] postData: (
"Snap (-LNAfBgHiac83feC6Wm1) {\n price = 3747;\n text = Jfjfjf;\n title = Jfjfjf;\n}",
"Snap (-LNAfY-W7OZMA4Jm7TQN) {\n price = 3764647;\n text = Kgkgkg;\n title = Blnckckc;\n}",
"Snap (-LNArUfHbIV3y_hgACLr) {\n title = Kgjggkkgnnc;\n}"
)

So it was that simple like
[self.postData addObject:child];
change to
[self.postData addObject:child.value];

Related

Firebase database query by key value

I have JSON like this.
livefeeds= {
"-KTn8pbqFHBUvgJ1Gwyl" = {
category = Alerts;
text = "Samsung Galaxy Note 7 owners told to turn off device";
timestamp = 1476179485648;
"user_id" = V7EFBV6uATf8urLXX9eK4EHhxmG2;
};
"-KTn8pbrhHyNzeLh2vOq" = {
category = News;
text = "Chicago Teachers Union, school board reach tentative contract agreement";
timestamp = 1476179485648;
"user_id" = V7EFBV6uATf8urLXX9eK4EHhxmG2;
};
}
I need to make query based on the key category.
Ex: If I only want Alerts, it should only retrieve category value equal to "Alerts" data only.
Here is query to retrieve livefeeds.
[[self.ref queryOrderedByChild:#"livefeeds"] observeEventType:FIRDataEventTypeValue withBlock:^(FIRDataSnapshot * _Nonnull snapshot) {
NSLog(#"---> %#",snapshot.value);
}];
First go till child "livefeeds" and then "queryOrderedByChild" category and use equal to child like this way
[[[[self.ref child:#"livefeeds"] queryOrderedByChild:#"category"]
queryEqualToValue:groupId]
observeEventType:FIRDataEventTypeValue withBlock:^(FIRDataSnapshot * _Nonnull snapshot) {
if (snapshot.value != [NSNull null]){
for (NSDictionary *snap in [snapshot.value allValues]) {
NSLog(#"---> %#",snap);
}
}
}];

Firebase sort query gives (unsorted) dictionary results

So I'm sure I'm missing something here, but when I wish to do a query for, say, the top 10 scores in a certain game, Firebase returns the top 10 scores, however since they are then gives back as a dictionary (key generated with childByAutoId), they are 'unsorted' when received on the client side (so to display a top 10 you have to sort them again)...
FIRDatabaseReference *ref = [[FIRDatabase database] reference];
FIRDatabaseQuery *jungleHighscoresQuery = [[[ref child:#"jungleScores"] queryOrderedByChild:#"score"] queryLimitedToLast:4];
[jungleHighscoresQuery observeSingleEventOfType:FIRDataEventTypeValue withBlock:^(FIRDataSnapshot * _Nonnull snapshot){
NSDictionary *postDict = snapshot.value;
NSLog(#"%#", postDict);
}];
The above code gives the following output (these are the top 4 scores among the ~20 in the database):
{
"-KIUhe_9TLQoy_zNbJT0" = {
score = 290;
userid = oMqoPGJYsGWHffYx8N6vDk3Osh72;
};
"-KIUj8VUyNMgyZ135dI_" = {
score = 560;
userid = oMqoPGJYsGWHffYx8N6vDk3Osh72;
};
"-KIUjK15Gy9PRB_JBWOA" = {
score = 240;
userid = oMqoPGJYsGWHffYx8N6vDk3Osh72;
};
"-KIUlZ1a03r7bjPYNueG" = {
score = 740;
userid = oMqoPGJYsGWHffYx8N6vDk3Osh72;
};
}
I know it's an easy task to just sort it all again, but it seems weird to have to do.
There was an easy solution after all, just had to grab the enumerator instead of the dictionary:
NSEnumerator *enumerator = snapshot.children;
and then just iterate through them with [enumerator nextObject]

Objective C - How do I convert this NSArray to an NSDictionary so I can look up city names by zip code?

I use Parse as my backend, and have a cloud function (written in javascript) that just returns an array
var providerZIPToCity = [ {zip:"48393", city:"WIXOM, MI"},{zip:"48116", city:"48116, MI"},{zip:"48114", city:"BRIGHTON, MI"},{zip:"48189", city:"WHITEMORE LAKE, MI"},{zip:"48178", city:"SOUTH LYON, MI"},{zip:"48168", city:"NORTHVILLE, MI"},{zip:"48167", city:"NORTHVILLE, MI"},{zip:"48375", city:"NOVI, MI"},{zip:"48374", city:"NOVI, MI"},{zip:"48165", city:"NEW HUDSON, MI"},{zip:"48377", city:"NOVI, MI"},{zip:"48390", city:"WALLED LAKE, MI"},{zip:"48381", city:"MILFORD, MI"},{zip:"48226", city:"DETROIT, MI"},{zip:"48201", city:"DETROIT, MI"}];
When I return this and print it out using the following objective c code in my app, I get the results below:
[PFCloud callFunctionInBackground:#"zipToCity" withParameters:#{} block:^(NSArray *results, NSError *error)
{
[_activityIndicator stopAnimating];
if( !error )
{
NSLog(#"%#",results);
}
else
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"CITY LOOKUP FAILED" message:#"We've failed to look up the city names for these ZIP codes. Try reloading this page from the menu. If the problem persists, you may not have a data or Wi-Fi connection." delegate:self cancelButtonTitle:#"OK" otherButtonTitles: nil];
alert.tag = 0;
[alert show];
}
}];
returns:
2015-06-10 17:25:04.444 XXXXXXXXX[266:18098] (
{
city = "WIXOM, MI";
zip = 48393;
},
{
city = "48116, MI";
zip = 48116;
},
{
city = "BRIGHTON, MI";
zip = 48114;
},
{
city = "WHITEMORE LAKE, MI";
zip = 48189;
},
{
city = "SOUTH LYON, MI";
zip = 48178;
},
{
city = "NORTHVILLE, MI";
zip = 48168;
},
{
city = "NORTHVILLE, MI";
zip = 48167;
},
{
city = "NOVI, MI";
zip = 48375;
},
{
city = "NOVI, MI";
zip = 48374;
},
{
city = "NEW HUDSON, MI";
zip = 48165;
},
{
city = "NOVI, MI";
zip = 48377;
},
{
city = "WALLED LAKE, MI";
zip = 48390;
},
{
city = "MILFORD, MI";
zip = 48381;
},
{
city = "DETROIT, MI";
zip = 48226;
},
{
city = "DETROIT, MI";
zip = 48201;
}
)
I have a bunch of labels that contain various zip codes that I need to iterate through, and change a label next to the zip code to be the city name associated with that zip code. I need to use that array, results,to either build an NSDictionary, or somehow access those city names by zip code from the current set up.
Problem is, I'm a bit of an objective C noob and I'm not entirely sure how this data is stored in the array. What type are the objects in this NSArray? They don't appear to be dictionaries to me. I'm a bit stumped, just not familiar with the data type enough to figure out how to do the lookup I need.
Could anyone point me in the right direction for how I could either create an NSMutableDictionary, which I do know how to look up values (city name strings) by keys ( zip codes ), or how I can iterate through my zip code labels and look up the city names directly with this NSArray?
I'm picturing either
NSMutableDictionary *ZIPsToCitiesDictionary = [NSMutableDictionary new];
for( int i = 0; i < [results count]; i++ )
{
//get element, i.e. ( {city = "WIXOM, MI"; zip = 48393;} )
//create new NSMutableDictionary element
[ZIPsToCitiesDictionary setObject: <city> forKey: <zip>];
}
then I can use the label.text parameter to access the city names,
or:
NSArray *ZIPLabelArray = ...;
NSMutableArray cityLabelArray = [NSMutableArray new]; //indexes correspond with ZIPLabelArray indexes
for( int i = 0; i < [ZIPLabelArray count]; i++ )
{
[cityLabelArray addObject: <city name somehow extracted from results by looking up the zip code at ZIPLabelArray[i]> ];
}
I appreciate any tips.
The elements of your array are indeed dictionaries. To test this, you can do something like:
NSLog(#"%#", NSStringFromClass(results[0]));
You were very close. You could do:
NSMutableDictionary *ZIPsToCitiesDictionary = [NSMutableDictionary new];
for(NSDictionary* dict in results)
{
NSString* city = dict[#"city"];
NSString* zip = dict[#"zip"];
[ZIPsToCitiesDictionary setObject:city forKey:zip]; // or ZIPsToCitiesDictionary[zip] = city
}
Update to account for multiple cities sharing the same zip:
NSMutableDictionary *ZIPsToCitiesDictionary = [NSMutableDictionary new];
for(NSDictionary* dict in results)
{
NSString* city = dict[#"city"];
NSString* zip = dict[#"zip"];
NSMutableArray* citiesForZip = ZIPsToCitiesDictionary[zip];
if (!citiesForZip)
{
citiesForZip = [NSMutableArray new];
ZIPsToCitiesDictionary[zip] = citiesForZip;
}
[citiesForZip addObject:city];
}
This will produce a dictionary mapping a zip code to an array of cities.
A more succinct way
NSArray *filteredByZip = [results filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:#"zip == '48393'"]];
This will return an array of items that match the condition zip == 48393.

Parsing JSON Dictionary elements into an NSArray

I am trying to parse a JSON response into an NSArray for a specific item (geometry/location/lat). I easily manage to get the name into an array with
for (NSDictionary *object in results)
{
NSString *objectName = object[#"name"];
[MyArray addObject:objectName];
}
but I don't know how to dig down to the "lat" level in order to extract this...
JSON DATA full results: (
{
geometry = {
location = {
lat = “15.122494";
lng = “45.518496";
};
};
icon = "http://maps.gstatic.com/mapfiles/place_api/icons/generic_business.png";
id = 1767ee03046d7ac7273be472310cfb6d7b2e6;
name = “Cafe Syracuse”;
photos = (
{
height = 768;
"html_attributions" = (
"From a Google User"
);
"photo_reference" = "CnRoAAAAlVZmfP0Dn3HIwcaEozcjYHqPMC_VlWcvz2sH0yYNjv9DS1GIccAvAp-LNaWxAWKvnEifhPU-1b8ETx7sXtOR7UKSs7tOBpai4FPM1y6M-lcL2qJ4M0dizbHStidxuGCF_QnE548qsE1tP2ZTdhjY_BIQKxSTS_-rPxGlOZmAG7oUUBSiV276H4CemarEXRozEtVr5Vs";
width = 1024;
}
);
"place_id" = ChIJB6K6CExRr8f4AvaA09U;
rating = "4.5";
reference = "CnRjAAAA5Yh4QrEnn7xH2URR7-gwwrhbUz2qmlwbCRW4-JkMfINdldXIYhQR8p2kTdiZiYsdX67nwINp963XIxysFPWOAVZ-okFCu0VH9NL66EWiPSVBFGSgYKXCd7LuhOFMgeU1yLuegyCMQ7RX6mjkhIQiVVok262SeOJGsChxoUXx6DKhp7t_uM51w2y9_bJAlscAA";
scope = GOOGLE;
types = (
cafe,
establishment
);
vicinity = “White glacier";
},
{
geometry = //Other item
Many thanks
This would help you to get lat and long:
NSString*lat= [[[object valueForKey:#"geometry"] valueForKey:#"location"] valueForKey:#"lat"];
NSString *lng= [[[object valueForKey:#"geometry"] valueForKey:#"location"] valueForKey:#"lng"];

How to extract elements in NSArray using NSPredicate

I have an array (NSArray) with the following content:
dates {
dateOne = {
"date_one" = "2011-11-30";
name = "test1";
dateOne=true
};
dateTwo = {
"date_two" = "2011-11-30";
name = "test2";
dateTwo=false
};
dateThree = {
"date_Three" = "2011-11-30";
dateTwo=true;
name = "test3";
};
the content above is being generating with the following line of code:
NSArray *dates = [myXmlParsed valueForKeyPath:#"myXml.dates"];
using NSLog:
NSLog(#"%#, '%#'", NSStringFromClass([dates class]), dates);
I get the following output:
__NSDictionaryM, '{
dateOne = {
"date_one" = "2011-11-30";
name = "test1";
dateOne=true
};
dateTwo = {
"date_two" = "2011-11-30";
name = "test2";
dateTwo=false
name = "test3";
};
dateThree = {
"date_Three" = "2011-11-30";
name = "test1";
dateTwo=true;
name = "test3";
};
}'
but I'm having problems getting the values of dictionaries inside of the array. My question is how can get the data of dateThree and how can I access to individual node of information for example date_Three ?
I'll really appreciate your help guys
I figure it out. I was using nsarray when I should have done nsmutabledictionary.
NSMutableDictionary *dates=[[NSMutableDictionary alloc] initWithDictionary: [resultDict valueForKeyPath:#"myXml.dates"]];
Now I can query any of the values:
NSLog(#"value %#", [[dates valueForKey:#"dateOne"] valueForKey:#"date_one"]);

Resources