Getting index of an String value within an array of array - ios

I have an unique scenario of getting index value of an element, where the structure is
Array - within Array - within Dictionary
(
{
STS = OPEN;
"STS_ICON" = "LIGHT_GREY";
},
"Headerquarter Planning"
),
(
{
STS = INPR;
"STS_ICON" = "LIGHT_BLUE";
},
"In Process"
),
(
{
STS = COMP;
"STS_ICON" = "LIGHT_GREEN";
},
Released
),
(
{
STS = CANC;
"STS_ICON" = "LIGHT_RED";
},
"ON HOLD - Call Transfer Delay"
)
)
iN THIS Case let's say i want index of #"ON HOLD - Call Transfer Delay" string.
I tried with like this..
NSUInteger index;
if([listOfStatus containsObject: list.statusType])
{
index = [listOfStatus indexOfObject: list.statusType];
}
where list.statusType is #"ON HOLD - Call Transfer Delay". But here i am getting "index" some weird value 15744929.

Try
- (NSInteger)findIndexOfStatus:(NSString *)status
{
NSString *filePath = [[NSBundle mainBundle]pathForResource:#"Status"
ofType:#"json"];
NSData *data = [[NSData alloc]initWithContentsOfFile:filePath];
NSArray *listOfStatus = [NSJSONSerialization JSONObjectWithData:data
options:0
error:nil];
NSPredicate *predicate = [NSPredicate predicateWithBlock:^BOOL(NSArray *evaluatedObject, NSDictionary *bindings) {
//NSDictionary *dict = evaluatedObject[0];
//return [dict[#"STS"] isEqualToString:status];
NSString *statusType = evaluatedObject[1];
return [statusType isEqualToString:status];
}];
return [listOfStatus indexOfObjectPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop) {
return [predicate evaluateWithObject:obj];
}];
}
You can find the index by calling
NSInteger index = [self findIndexOfStatus:#"ON HOLD - Call Transfer Delay"];
I have also commented out an option to find out if you want to use the status code.
The Status.json file

Related

NSDictionary get property within list of objects - Objective C

How would I get "Dog" from the following dictionary?
{
Id = "123";
Animal = [{
Id = "456";
Type = "Dog";
Sound = "Bark";
},
{
Id = "789";
Type = "Cat";
Sound = "Meow";
}]
}
I tried
NSString *firstAnimalType = dictionary[#"Animal"][#"Type"];
However since there are multiple animals, it can't recognize what I am trying to find. How would I get the first animal out of the list so that I can access its type? Thanks!
You can use some thing like this, first get animal object and if it exists then find its type from it
NSDictionary *firstAnimal = [dictionary[#"Animal"] firstObject];
if(firstAnimal) //in case your firstAnimal is Empty or it may be nil then may create any unwanted issues in further code so just check it first.
{
NSString *firstAnimalType = firstAnimal[#"Type"];
}
Enumeration method will help and you can stop when and where you want
[myDict[#"Animal"] enumerateObjectsUsingBlock:^(id _Nonnull objList, NSUInteger idx, BOOL * _Nonnull stop) {
NSLog(#"%#",objList[#"Type"]);
*stop = YES; //You can stop where you want
}];
You can simply access the first element of the array with castings and get its Type value.
NSString *firstAnimalType = ((NSDictionary *)[((NSArray *)dictionary[#"Animal"]) objectAtIndex: 0])[#"Type"];
for (NSDictionary *animal in dictionary[#"Animal"]) {
NSString *type = animal[#"Type"];
if ([type isKindOfClass:[NSString class]] && [type isEqualToString:#"Dog"]) {
// Dog found
}
}
Here you go:
NSArray *aryFinalAni = [dicMain valueForKey:#"Animal"];
NSArray *aryType = [aryFinalAni valueForKeyPath:#"Type"];
if([aryType containsObject:#"Dog"])
{
int indexOfDog = (int)[aryType indexOfObject:#"Dog"];
NSMutableDictionary *dicDog = [aryFinalAni objectAtIndex:indexOfDog];
NSLog(#"%#",dicDog);
}
else
{
NSLog(#"There is no Dog found.");
}
Try this code:
{
Id = "123";
Animal = [{
Id = "456";
Type = "Dog";
Sound = "Bark";
},
{
Id = "789";
Type = "Cat";
Sound = "Meow";
}]
}
1> NSArray *items = dictionary["Animal"];
2>
NSPredicate *predicate1 = [NSPredicate predicateWithFormat: #"Type CONTAINS[cd] %#", "Dog"];
NSArray *arrData = [items filteredArrayUsingPredicate:predicate1];
if arrData.count > 0 {
dictionary = [arrData objectAtIndex:0];
}
Result:
{
Id = "456";
Type = "Dog";
Sound = "Bark";
}

New to JSON API how to access the values in objective-c?

Below is my code to access the JSON API from Edmunds.com, this works perfectly to access the information I am just having trouble with accessing the key, value pairs.
NSURL *equipmentURL = [NSURL URLWithString: [NSString stringWithFormat:#"https://api.edmunds.com/api/vehicle/v2/styles/%#/equipment?fmt=json&api_key=%#", self.carID, apiKey]];
NSData *jsonData = [NSData dataWithContentsOfURL:equipmentURL];
NSError *error = nil;
NSDictionary *dataDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
self.engineArray = [NSMutableArray array];
NSArray *equipmentArray = [dataDictionary objectForKey:#"equipment"];
for (NSDictionary *carInfoDictionary in equipmentArray) {
NSArray *attributes = [carInfoDictionary objectForKey:#"attributes"];
NSLog(#"%#", attributes);
}
In the NSLog from the above code shows this:
2016-11-03 10:21:26.029 CarWise[25766:1896339] (
{
name = "Engine Immobilizer";
value = "engine immobilizer";
},
{
name = "Power Door Locks";
value = "hands-free entry";
},
{
name = "Anti Theft Alarm System";
value = "remote anti-theft alarm system";
}
)
My main question is how can I access the name and value for each array? Let's say I want to create a UILabel that will have the string of one of the values?
Probably this will help
// Array as per the post
NSArray *attributes = (NSArray *)[carInfoDictionary objectForKey:#"attributes"];
// Loop to iterate over the array of objects(Dictionary)
for (int i = 0; i < attributes.count; i++) {
NSDictionary * dataObject = [NSDictionary dictionaryWithDictionary:(NSDictionary *)attributes[i]];
// This is the value for key "Name"
NSString *nameData = [NSString stringWithString:[dataObject valueForKey:#"name"]];
NSLog(#"Value of key : (name) : %#", nameData);
}

How To Get Particular Values From Json Response Using Objective C?

I am trying to get response of first key value without mentioning key name of "A" using objective C. I cant get exactly, please help me to get from below response.
NSDictionary *JSON = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves | NSJSONReadingMutableContainers error:&error];
NSDictionary *response = [JSON[#"response"]firstObject];
response = {
A = {
company = (
{
no = "115";
student = "Mich";
school = (
{
grade = A;
}
);
test = "<null>";
office = tx;
}
);
};
}
There are a few ways to do this, depending on your exact requirements. If you just need to access the value of each key in JSON[#"response"], you can enumerate the JSON dictionary:
[JSON enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
NSDictionary *dict = (NSDictionary *)obj;
...
if (shouldStop) { // whatever condition you want, if any
*stop = YES;
}
}];
If you want some kind of ordering, you need to use [JSON allKeys]:
NSArray *keys = [[JSON allKeys] sortedArrayUsing...]; // Use whichever sort method you like
for (NSString *key in keys) {
NSDictionary *dict = JSON[key];
...
}
If all you want are the values, you can use [JSON allValues]. Sort if desired.

Parsing values from NSArray based on JSON format

I have a NSArray which is based on JSON format. I requested it from the web and saved it in the array. I am trying to use a dictionary to get the values of "categoryname" and "subscore" and store them in new arrays, but they remain empty. Do I have to convert the array back to NSData using JSON serialisation or is there a more direct way to achieve this?
NSArray detailedscore:
{
"articles": [
{
"abstract": "text",
"title": "title"
}
],
"subscore": 3,
"categoryname": "Reporting"
},
{
"articles": [
{
"abstract": "text2",
"title": "title"
}
],
"subscore": 1,
"categoryname": "Power"
}]
}
Code:
for(int i = 0; i < [self.detailedscore count]; i++)
{
NSMutableDictionary * dc = [self.detailedscore objectAtIndex:i];
NSString * score = [dc objectForKey:#"subscore"];
NSString * categoryname = [dc objectForKey:#"categoryname"];
[self.allscores addObject:subscore];
[self.allcategories addObject:categoryname];
for (NSString *yourVar in allcategories) {
NSLog (#"Your Array elements are = %#", yourVar);
}
{} ----> means dictionary, []---> array..... this is a rule I follow while assinging the return value from webservices as NSArray or NSDictionary....
Depending on your current JSON format, perhaps this might give you an idea
NSMutableArray *categoryArray = [NSMutableArray new];
for (NSDictionary *childDict in self.detailedscore)
{
[categoryArray addObject:[childDict objectForkey:#"categoryname"]];
}
If you have the array use below code
for(int i = 0; i < [self.detailedscore count]; i++)
{
NSMutableDictionary * dc = [self.detailedscore objectAtIndex:i];
NSString * score = [dc objectForKey:#"subscore"];
NSString * categoryname = [dc objectForKey:#"categoryname"];
[self.allscores score];
[self.allcategories addObject:categoryname];
for (NSString *yourVar in allcategories) {
NSLog (#"Your Array elements are = %#", yourVar);
}
The problem wasn't in the array or dictionary or the web request. I didn't allocated the NSMutableArrays so they were empty all the time. The code works fine for extracting values from the array in case anyone wants to use it.
Hope this helps.
[NSURLConnection sendAsynchronousRequest:req queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
if (!connectionError) {
NSDictionary *dict=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&connectionError];
NSLog(#"Dict %#",dict);
BOOL isValid = [NSJSONSerialization isValidJSONObject:dict];
if (isValid) {
[target getJSONFromresponseDictionary:dict forConnection:strTag error:connectionError];
}
else{
NSString *strResponse = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
[target getStringFromresponseDictionary:strResponse forConnection:strTag error:error];
}

iOS MKMapItem - how get access to all members?

I am using MapKit to do a local search which returns one or more MKMapItem objects. But there are members of the object I can see in the debugger but I can't access. The one I particularly need is UID.
I have tried item.placemark, but it does not let me access the UID. This seems like it should be really simple. What am I missing here?
This does not work:
NSString *uid = item.placemark.UID
This does not work:
NSDictionary *mapItemDictionary = (NSDictionary *)item;
NSString *uid = [mapItemDictionary objectForKey:#"UID"];
But the debugger command po item shows me all the members of the object:
Name: Shell CurrentLocation: 0 Place: <GEOPlace: 0x17014e650>
{
address = {
business = (
{
**UID = 2478578482074921045**;
URL = "www.shell.com";
canBeCorrectedByBusinessOwner = 1;
name = Shell;
source = (
{
"source_id" = A3H0281540;
"source_name" = "acxiom_us";
},
{
"source_id" = 2276257;
"source_name" = localeze;
}
);
telephone = "+14803968213";
}
);
Any help with this would be appreciated. Here is the code I'm using:
MKLocalSearch *localSearch = [[MKLocalSearch alloc] initWithRequest:request];
[localSearch startWithCompletionHandler:^(MKLocalSearchResponse *response, NSError *error)
{
[response.mapItems enumerateObjectsUsingBlock:^(MKMapItem *item, NSUInteger idx, BOOL *stop)
{
MKPlacemark *placemark = (MKPlacemark *)item.placemark;
NSDictionary *addressDict = placemark.addressDictionary;
NSArray *businessArray = addressDict[#"business"];// businessArray is NIL
NSString *uid=nil;
if (businessArray != nil && businessArray.count >0) {
NSDictionary *businessDict=businessArray[0];
uid=businessDict[#"UID"];
}
NSLog(#"UID is %#",uid);
}];
Ok, so after a lot of digging it seems that the information is in a couple of private objects. The "place" property is a GEOPlace, and this has a property, business, which is an array that contains a GEOBusiness object. Since this is private data you cannot access it directly via properties, but you can get it via key-value encoding. The following code extracts the UID -
[response.mapItems enumerateObjectsUsingBlock:^(MKMapItem *item, NSUInteger idx, BOOL *stop) {
NSValue *place = [item valueForKey:#"place"];
NSArray *businessArray = (NSArray *)[place valueForKey:#"business"];
NSNumber *uid=nil;
if (businessArray != nil && businessArray.count >0) {
id geobusiness=businessArray[0];
uid=[geobusiness valueForKey:#"uID"];
}
NSLog(#"UID is %#",[uid stringValue]);
}];
As this is private data structures there is no guarantee that it won't change. I am also unsure whether the App store validation process will flag this as private api access - Since it is using valueForKey I don't think it will, but there are no guarantees.

Resources