I have got a small problem with the below service data
{
"DataTable": {
"DataList1": {
"StudentName": "Rakesh",
"StudentId": "13",
"StudentAge": "19",
"StudentAddress": "NewYork",
},
"DataList2": [{
"TeacherName": "Abhinav",
"TeacherId": "309",
"TeacherAge": "34",
"TeacherAddress": "NewYork",
}]
}
}
i Can get the data from DataList1 and cannot know how to get the data from DataList2. Below is the code what i have tried. Please help to find out the solution. Thanks in Advance
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
[jsonArray removeAllObjects];
NSString *responseString = [[NSString alloc] initWithData:self.responseData encoding:NSUTF8StringEncoding];
self.responseData = nil;
NSMutableDictionary *sdf = [(NSDictionary*)[responseString JSONValue] objectForKey:#"DataTable"];
NSMutableArray * myArray = [[NSMutableArray alloc] init];
if (([(NSString*)sdf isEqual: [NSNull null]])) {
UIAlertView *alert=[[UIAlertView alloc]initWithTitle:#"Information" message:#"Currently there are no Data" delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[alert setTag:1];
[alert show];
}else {
[myArray addObject:[sdf objectForKey:#"DataList1"]];
jsonArray=[myArray mutableCopy];
refilldict=[jsonArray objectAtIndex:0];
NSArray *keys = [refilldict allKeys];
for(int p=0 ; p<[keys count]; p++ )
{
NSString *value=[refilldict objectForKey:[keys objectAtIndex:p]];
if ([value isEqual: [NSNull null]]||[value length]==0) {
[refilldict setValue:#"" forKey:[keys objectAtIndex:p]];
}
}
lblStudentName.text = [refilldict objectForKey:#"StudentName"];
lblStudentId.text = [refilldict objectForKey:#"StudentId"];
lblStudentAge.text = [refilldict objectForKey:#"StudentAge"];
lblStudentAddress.text = [refilldict objectForKey:#"StudentAddress"];
}
self.navigationController.navigationBar.userInteractionEnabled = YES;
[HUD hide:YES];
[HUD removeFromSuperview];
HUD=nil;
}
Please use the bellow code and pass your Initial Json dictionary in it.
-(void)parseJsonData:(NSDictionary *)jsonDictionary{
for(int i=0;i<[jsonDictionary allKeys].count;i++){
NSString *keyName = [[jsonDictionary allKeys] objectAtIndex:i];
id objValue = [jsonDictionary objectForKey:keyName];
if([objValue isKindOfClass:[NSArray class]]){
NSArray *dataList2Array = (NSArray *)objValue;
NSLog(#"DataList2 Is :--%#",dataList2Array);
}
else {
NSDictionary *dataList1 = (NSDictionary *)objValue;
NSLog(#"DataList1 Is :--%#",dataList1);
}
}
}
you can get easily like
[myArray addObject:[sdf objectForKey:#"DataList1"]];
its started with array of dictionary , so you need to store your second object to array and take from index.
NSArray *temp = [sdf objectForKey:#"DataList2"];
if(temp.count >0)
{
lblTeacherName.text = temp[0][#"TeacherName"];
lblTeacherId.text = temp[0][#"TeacherId"];
lblTeacherAge.text = temp[0][#"TeacherAge"];
lblTeacherAddress.text = temp[0][#"TeacherAddress"];
}
Related
here is my code. I used NSDictionary and coded to print my json data in my console.but i got error like this:
'NSInvalidArgumentException', reason: '-[__NSCFString objectForKeyedSubscript:]: unrecognized selector sent to instance 0x7c971930'
My code:
if(buttonIndex == 0) {
NSLog(#"OK Button is clicked");
}
else if(buttonIndex == 1) {
if([[textView.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length]!=0)
{
if(!self.note)
{
NSManagedObjectContext *context = [self managedObjectContext];
NSManagedObject *newNote = [NSEntityDescription insertNewObjectForEntityForName:#"Notes" inManagedObjectContext:context];
NSLog(#"%#",textView.text);
[newNote setValue:textView.text forKey:#"note"];
if([textView.text length]>30)
{
[newNote setValue:[NSString stringWithFormat:#"%#...",[textView.text substringToIndex:25]] forKey:#"title"];
}
else
[newNote setValue:textView.text forKey:#"title"];
[newNote setValue:[NSDate date] forKey:#"mod_time"];
//[newDevice setValue:self.versionTextField.text forKey:#"version"];
//[newDevice setValue:self.companyTextField.text forKey:#"company"];
How to overcome this problem to work and to print my data in my console
Help me out. I am struggling for 2 hours.I googled and change all change.But cant get data in my console. Thanks in advance
I guess you can get data like below this
NSDictionary *monday = jsonResults[#"original"];
NSArray * arrFile = monday[#"files"];
for (NSDictionary *theCourse in arrFile)
{
....
}
Did you checked that received data (i.e., returnData) from sendSynchronousRequest: is returning a plain data?
If the data received is in Base64, you might have to decode this NSData to plain data, and then go ahead with String conversion.
NSData *decodedData = [[NSData alloc] initWithBase64EncodedData:responseData options:NSDataBase64DecodingIgnoreUnknownCharacters];
NSString *str = [[NSString alloc] initWithData:decodedData encoding:NSUTF8StringEncoding];
// convert Json to NSDictionary
NSDictionary *jsonResults = [NSJSONSerialization JSONObjectWithData:returnData options:NSJSONReadingMutableContainers error:nil];
// NSLog(#"%#",jsonResults);
int count = [[jsonResults valueForKey:#"count"] intValue];
NSArray *arrayData = [jsonResults copy];
NSMutableArray *arrayPDFName = [[NSMutableArray alloc]init];
for(int i = 0;i < [arrayData count];i++)
{
NSDictionary *dictOriginal = [[arrayData objectAtIndex:2]valueForKey:#"original"];
int countOriginal = [[dictOriginal valueForKey:#"count"] intValue];
NSLog(#"The countOriginal is - %d",countOriginal);
NSArray *arrayFiles = [[dictOriginal valueForKey:#"files"] copy];
NSLog(#"The arrayFiles are - %#",arrayFiles);
for(int j=0;j<[arrayFiles count];j++)
{
NSString *strCreatedTime = [NSString stringWithFormat:#"%#",[[arrayFiles objectAtIndex:j] valueForKey:#"created_time"]];
NSString *strLastModifiedTime = [NSString stringWithFormat:#"%#",[[arrayFiles objectAtIndex:j] valueForKey:#"last_modified_time"]];
NSString *strID = [NSString stringWithFormat:#"%#",[[arrayFiles objectAtIndex:j] valueForKey:#"id"]];
NSString *strName = [NSString stringWithFormat:#"%#",[[arrayFiles objectAtIndex:j] valueForKey:#"name"]];
NSLog(#"The created_time is - %#",strCreatedTime);
NSLog(#"The last_modified_time is - %#",strLastModifiedTime);
NSLog(#"The is is - %#",strID);
NSLog(#"The name is - %#",strName);
[arrayPDFName addObject:strName];
}
}
I have an issue that an array having three main objects and i want to add one object on each array's 0 index
Here is URL link
In three sections Homes Plots and Commercial and i want to add All Homes All Plots and All Commercial in each section and added up their results in each section, mean in each section at top All Homes, All Plots and All Commercial
- (void) loadFromDictionary:(NSDictionary *)theDictionary{
_parent_id = -1;
_type_id = [[theDictionary objectForKey:#"type_id"] intValue];
_title = [[NSString alloc] initWithString:[theDictionary objectForKey:#"title"]];
_title_alt1 = [[NSString alloc] initWithString:[theDictionary objectForKey:#"title_alt1"]];
_title_alt2 = [[NSString alloc] initWithString:[theDictionary objectForKey:#"title_alt2"]];
if([theDictionary objectForKey:#"parent_id"])
_parent_id = [[theDictionary objectForKey:#"parent_id"] intValue];
if([theDictionary objectForKey:#"child_list"])
_child_list = [[NSMutableArray alloc] initWithArray:[[theDictionary objectForKey:#"child_list"] componentsSeparatedByString:#","]];
}
+ (void)getTypesWith:(void (^)(NSArray *, NSError *))completionHandler
{
[ZNetworkManager postDataForBackGround:nil atURL:[ZMappingManager getRequestURLToGetPropertiesTypes] completionHandler:^(NSArray *array, NSError *error)
{
NSMutableArray *typesDictionariesArray =[NSMutableArray array];
NSMutableDictionary* details = [NSMutableDictionary dictionary];
if (!error)
{
NSDictionary *fetchedDictionary = (NSDictionary*) array;
if([fetchedDictionary isKindOfClass:[NSDictionary class]] == NO)
{
[details setValue:#"Fetched dictionary is null" forKey:#"desription"];
completionHandler(nil ,[NSError errorWithDomain:#"MyDomain" code:1 userInfo:details]);
}
else
{
if([[[fetchedDictionary objectForKey:#"meta"] objectForKey:#"status"] isEqualToString:#"200"]){
NSDictionary *data = [fetchedDictionary objectForKey:#"response"];
if([data isKindOfClass:[NSDictionary class]] == NO)
{
[details setValue:#"Fetched dictionary is null" forKey:#"desription"];
completionHandler(nil ,[NSError errorWithDomain:#"MyDomain" code:1 userInfo:details]);
}
else
{
NSArray *allTypes = [data objectForKey:#"type"];
if([allTypes count] == 0)
{
[details setValue:#"Fetched dictionary is null" forKey:#"desription"];
completionHandler(nil ,[NSError errorWithDomain:#"MyDomain" code:1 userInfo:details]);
}
else
{
NSMutableArray *searchTypes = [[NSMutableArray alloc] init];
for (NSDictionary *typeDic in allTypes)
{
[typesDictionariesArray addObject:typeDic];
ZZameenType *newType = [[ZZameenType alloc] init];
[newType loadFromDictionary:typeDic];
[searchTypes addObject:newType];
NSArray *arrayforChild = [typeDic objectForKey:#"childs"];
for(NSDictionary *typeChild in arrayforChild){
[typesDictionariesArray addObject:typeChild];
ZZameenType *newChild = [[ZZameenType alloc] init];
[newChild loadFromDictionary:typeChild];
[searchTypes addObject:newChild];
newChild = nil;
}
newType = nil;
}
NSSortDescriptor *typeID_sort = [NSSortDescriptor sortDescriptorWithKey:#"type_id" ascending:YES];
[searchTypes sortUsingDescriptors:[NSArray arrayWithObjects:typeID_sort,nil]];
[ZGlobals saveSearchTypes:typesDictionariesArray];
completionHandler(searchTypes ,nil);
searchTypes = nil;
details = nil;
}
}
}else{
}
}
}
}];
}
Not entirely sure what issue you're having. If you're just wanting to insert objects into an array and a specific index - you'd do something like this:
[searchTypes insertObject: addObject:newType atIndex:0];
I am newbie in iOS and i have an issue i parsed an array and show in table which having three sections and every each section i added new row to add up its all children in hierarchy but due to table reload issue its indexing change and show wrong results. here is my code below
+ (void)getTypesWith:(void (^)(NSArray *, NSError *))completionHandler
{
[ZNetworkManager postDataForBackGround:nil atURL:[ZMappingManager getRequestURLToGetPropertiesTypes] completionHandler:^(NSArray *array, NSError *error)
{
NSMutableArray *typesDictionariesArray =[NSMutableArray array];
NSMutableDictionary* details = [NSMutableDictionary dictionary];
if (!error)
{
NSDictionary *fetchedDictionary = (NSDictionary *) array;
if([fetchedDictionary isKindOfClass:[NSDictionary class]] == NO)
{
[details setValue:#"Fetched dictionary is null" forKey:#"desription"];
completionHandler(nil ,[NSError errorWithDomain:#"MyDomain" code:1 userInfo:details]);
}
else
{
if([[[fetchedDictionary objectForKey:#"meta"] objectForKey:#"status"] isEqualToString:#"200"]){
NSDictionary *data = [fetchedDictionary objectForKey:#"response"];
if([data isKindOfClass:[NSDictionary class]] == NO)
{
[details setValue:#"Fetched dictionary is null" forKey:#"desription"];
completionHandler(nil ,[NSError errorWithDomain:#"MyDomain" code:1 userInfo:details]);
}
else
{
NSArray *allTypes = [data objectForKey:#"type"];
if([allTypes count] == 0)
{
[details setValue:#"Fetched dictionary is null" forKey:#"desription"];
completionHandler(nil ,[NSError errorWithDomain:#"MyDomain" code:1 userInfo:details]);
}
else
{
NSMutableArray *searchTypes = [[NSMutableArray alloc] init];
for (int i=0; i<[allTypes count]; i++)
// for (NSDictionary *typeDic in allTypes)
{
NSDictionary *typeDic = [allTypes objectAtIndex:i];
[typesDictionariesArray addObject:typeDic];
ZZameenType *newType = [[ZZameenType alloc] init];
[newType loadFromDictionary:typeDic];
[searchTypes addObject:newType];
NSArray *arrayforChild = [typeDic objectForKey:#"childs"];
for (int j=0; j<[arrayforChild count]; j++)
// for(NSDictionary *typeChild in arrayforChild)
{
NSDictionary *typeChild = [arrayforChild objectAtIndex:j];
ZZameenType *newChild;
[typesDictionariesArray addObject:typeChild];
newChild = [[ZZameenType alloc] init];
[newChild loadFromDictionary:typeChild];
[searchTypes addObject:newChild];
if(j == 0)
{
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
NSString *combineString = [NSString stringWithFormat:#"All %#",[typeDic objectForKey:#"title_alt2"]];
[dict setObject:combineString forKey:#"title"];
[dict setObject:combineString forKey:#"title_alt2"];
[dict setObject:combineString forKey:#"title_alt1"];
[dict setObject:[typeDic objectForKey:#"type_id"] forKey:#"parent_id"];
[dict setObject:[typeDic objectForKey:#"child_list"] forKey:#"type_id"];
[typesDictionariesArray insertObject:dict atIndex:[typesDictionariesArray count]-1];
newChild = [[ZZameenType alloc] init];
[newChild loadFromDictionary:dict];
[searchTypes insertObject:newChild atIndex:[searchTypes count]-1];
}
}
newType = nil;
}
NSSortDescriptor *typeID_sort = [NSSortDescriptor sortDescriptorWithKey:#"type_id" ascending:YES];
[searchTypes sortUsingDescriptors:[NSArray arrayWithObjects:typeID_sort,nil]];
[ZGlobals saveSearchTypes:typesDictionariesArray];
completionHandler(searchTypes ,nil);
searchTypes = nil;
details = nil;
}
}
}else{
}
}
}
}];
}
cellForRowAtIndexPath
if(selectionC == nil) {
selectionC=[[[NSBundle mainBundle] loadNibNamed:#"SelectionCell" owner:self options:nil] objectAtIndex:0];
}
KLog(#"view frame is %#",NSStringFromCGRect(self.frame));
KLog(#"table frame is %#",NSStringFromCGRect(tableView.frame));
NSArray *values =[[ZGlobals getPropertTypeSectionsValues] objectAtIndex:indexPath.section];
ZZameenType *type =[values objectAtIndex:indexPath.row];
selectionC.selectionTitle.text = type.title;
selectionC.selectionTitle.textColor = [ZTheme cellValuesColorIPAD];
Hi i'm successfully loged in google plus. Now i'm trying to fetch friends details like emails, image, name.But getting error.
Please any one could help me, where i'm making mistake -
I tried this code -
- (void)finishedWithAuth: (GTMOAuth2Authentication *)auth
error: (NSError *) error {
self.plusService.authorizer = auth;
NSLog(#"%#",[NSString stringWithFormat:#"Email---> %#\n\n",[GPPSignIn sharedInstance].authentication.userEmail]);
NSLog(#"Received error %# and auth object ---> %#\n\n",error, auth);
// 1. Create a |GTLServicePlus| instance to send a request to Google+.
GTLServicePlus* plusService = [[GTLServicePlus alloc] init] ;
plusService.retryEnabled = YES;
// 2. Set a valid |GTMOAuth2Authentication| object as the authori zer.
[plusService setAuthorizer:[GPPSignIn sharedInstance].authentication];
// 3. Use the "v1" version of the Google+ API.*
plusService.apiVersion = #"v1";
GTLQueryPlus *query = [GTLQueryPlus queryForPeopleListWithUserId:#"me" collection:kGTLPlusCollectionVisible];
[plusService executeQuery:query
completionHandler:^(GTLServiceTicket *ticket,
GTLPlusPeopleFeed *person,
NSError *error) {
if (error)
{
GTMLoggerError(#"Error: %#", error);
}
else {
NSArray *peopleList = person.items;
NSLog(#"--People_List--->%#",peopleList);
}}];
}
Getting Error -
[lvl=3] __41-[ViewController finishedWithAuth:error:]_block_invoke() Error: Error Domain=com.google.GTLJSONRPCErrorDomain Code=401 "The operation couldn’t be completed. (Invalid Credentials)" UserInfo=0x7b0a1d10 {error=Invalid Credentials, GTLStructuredError=GTLErrorObject 0x7b089360: {message:"Invalid Credentials" code:401 data:[1]}, NSLocalizedFailureReason=(Invalid Credentials)}
for Fetching Friends Details you can use Google Contacts api
in that use
#import "GDataFeedContact.h"
#import "GDataContacts.h"
class file
then use this code to get data
-(void)getGoogleContacts
{
GDataServiceGoogleContact *service = [self contactService];
GDataServiceTicket *ticket;
BOOL shouldShowDeleted = TRUE;
const int kBuncha = 2000;
NSURL *feedURL = [GDataServiceGoogleContact contactFeedURLForUserID:kGDataServiceDefaultUser];
GDataQueryContact *query = [GDataQueryContact contactQueryWithFeedURL:feedURL];
[query setShouldShowDeleted:shouldShowDeleted];
[query setMaxResults:kBuncha];
ticket = [service fetchFeedWithQuery:query
delegate:self
didFinishSelector:#selector(contactsFetchTicket:finishedWithFeed:error:)];
[self setContactFetchTicket:ticket];
}
- (void)setContactFetchTicket:(GDataServiceTicket *)ticket
{
mContactFetchTicket = ticket;
}
- (GDataServiceGoogleContact *)contactService
{
static GDataServiceGoogleContact* service = nil;
if (!service) {
service = [[GDataServiceGoogleContact alloc] init];
[service setShouldCacheResponseData:YES];
[service setServiceShouldFollowNextLinks:YES];
}
//pass the useremail and password.here
NSString *username = #"youremai#gmail";
NSString *password = #"yourpassword";
[service setUserCredentialsWithUsername:username
password:password];
return service;
}
- (void)contactsFetchTicket:(GDataServiceTicket *)ticket
finishedWithFeed:(GDataFeedContact *)feed
error:(NSError *)error {
if (error) {
NSDictionary *userInfo = [error userInfo];
NSLog(#"Contacts Fetch error :%#", [userInfo objectForKey:#"Error"]);
if ([[userInfo objectForKey:#"Error"] isEqual:#"BadAuthentication"]) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Error!"
message:#"Authentication Failed"
delegate:self
cancelButtonTitle:#"Ok"
otherButtonTitles:nil, nil];
[alertView show];
} else {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Error!"
message:#"Failed to get Contacts."
delegate:self
cancelButtonTitle:#"Ok"
otherButtonTitles:nil, nil];
[alertView show];
}
} else {
NSArray *contacts = [feed entries];
NSLog(#"Contacts Count: %d ", [contacts count]);
[googleContacts removeAllObjects];
for (int i = 0; i < [contacts count]; i++) {
GDataEntryContact *contact = [contacts objectAtIndex:i];
// Name
NSString *ContactName = [[[contact name] fullName] contentStringValue];
NSLog(#"Name : %#", ContactName);
// Email
GDataEmail *email = [[contact emailAddresses] objectAtIndex:0];
NSString *ContactEmail = #"";
if (email && [email address]) {
ContactEmail = [email address];
NSLog(#"EmailID : %#", ContactEmail);
}
// Phone
GDataPhoneNumber *phone = [[contact phoneNumbers] objectAtIndex:0];
NSString *ContactPhone = #"";
if (phone && [phone contentStringValue]) {
ContactPhone = [phone contentStringValue];
NSLog(#"Phone : %#", ContactPhone);
}
// Address
GDataStructuredPostalAddress *postalAddress = [[contact structuredPostalAddresses] objectAtIndex:0];
NSString *address = #"";
if (postalAddress) {
NSLog(#"formattedAddress : %#", [postalAddress formattedAddress]);
address = [postalAddress formattedAddress];
}
// Birthday
NSString *dob = #"";
if ([contact birthday]) {
dob = [contact birthday];
NSLog(#"dob : %#", dob);
}
if (!ContactName || !(ContactEmail || ContactPhone) ) {
NSLog(#"Empty Contact Fields. Not Adding.");
}
else
{
if (!ContactEmail ) {
ContactEmail = #"";
}
if (!ContactPhone ) {
ContactPhone = #"";
}
NSArray *keys = [[NSArray alloc] initWithObjects:#"name", #"emailId", #"phoneNumber", #"address", #"dob", nil];
NSArray *objs = [[NSArray alloc] initWithObjects:ContactName, ContactEmail, ContactPhone, address, dob, nil];
NSDictionary *dict = [[NSDictionary alloc] initWithObjects:objs forKeys:keys];
[googleContacts addObject:dict];
}
}
NSSortDescriptor *descriptor =
[[NSSortDescriptor alloc] initWithKey:#"name" ascending:YES selector:#selector(localizedCaseInsensitiveCompare:)];
[googleContacts sortUsingDescriptors:[NSArray arrayWithObjects:descriptor, nil]];
get the more info refer this http://dipinkrishna.com/blog/2013/07/ios-google-contacts/4/
I am trying to use the data which I read from a text file in objective c. The data I read from the text file is:
{"aps":{"alert":"Test 1!","sound":"beep.wav","badge":5,"Type":"Banking"},"acme1":"bar","acme2":42}|{"aps":{"alert":"Test 2!","sound":"beep.wav","badge":5,"Type":"Banking"},"acme1":"bar","acme2":42}|{"aps":{"alert":"Test 3!","sound":"beep.wav","badge":5,"Type":"Banking"},"acme1":"bar","acme2":42}|{"aps":{"alert":"Test 4!","sound":"beep.wav","badge":5,"Type":"Banking"},"acme1":"bar","acme2":42}|{"aps":{"alert":"Test 5!","sound":"beep.wav","badge":5,"Type":"Banking"},"acme1":"bar","acme2":42}
Once read, I split the file into an array with a delimiter of "|". I then want to further separate it into 3 different arrays: banking, fraud and investment based on the key "Type". However I cannot seem to reach parse the JSON string once I split it into the array. My view did load method is below:
- (void)viewDidLoad {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fileName = [NSString stringWithFormat:#"%#/AccountNotifications.txt", documentsDirectory];
NSString *fileContents = [[NSString alloc] initWithContentsOfFile:fileName usedEncoding:nil error:nil];
NSArray *fileData = [fileContents componentsSeparatedByString:#"|"];
if (fileContents != NULL)
{
bankingNotifications = [[NSMutableArray alloc] init];
fraudNotifications = [[NSMutableArray alloc] init];
investmentNotifications = [[NSMutableArray alloc] init];
for (i = 0; i < [fileData count]; i++)
{
NSString *notification = fileData[i];
NSDictionary *json = [notification JSONValue];
NSArray *items = [json valueForKeyPath:#"aps"];
if ([[[items objectAtIndex:i] objectForKey:#"Type"] isEqual: #"Banking"])
{
[bankingNotifications addObject:fileData[i]];
NSLog(#"Added object to banking array");
}
if ([[[items objectAtIndex:i] objectForKey:#"Type"] isEqual: #"Fraud"])
{
[fraudNotifications addObject:fileData[i]];
NSLog(#"Added object to fraud array");
}
if ([[[items objectAtIndex:i] objectForKey:#"Type"] isEqual: #"Investment"])
{
[investmentNotifications addObject:fileData[i]];
NSLog(#"Added object to investment array");
}
} }
There is an error with these three lines:
NSString *notification = fileData[i];
NSDictionary *json = [notification JSONValue];
NSArray *items = [json valueForKeyPath:#"aps"];
Could you please help me parse the JSON strings into the three mutable arrays? The error I am getting is:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSDictionaryM objectAtIndex:]: unrecognized selector sent to instance 0x1d59db30'
If you create the text file yourself I would suggest you create a valid json object (as your data looks like it is supposed to be json) to keep your data nice and clean. similar to this:
{"aps":[{"type":"Banking","badge":5},{"Type":"Fraud","badge":12}]}
Then you can do following (this code is not tested, it can be that you have to amend it a bit) but i hope you'll get an idea :)
NSError* error = nil;
NSDictionary* dict = nil;
//serialising the jsonobject to a dictionary
dict = [NSJSONSerialization JSONObjectWithData:fileContents
options:kNilOptions
error:&error];
bankingNotifications = [[NSMutableArray alloc] init];
fraudNotifications = [[NSMutableArray alloc] init];
investmentNotifications = [[NSMutableArray alloc] init];
if (dict) {
NSArray *dataArray = [dict objectForKey:#"aps"];
NSDictionary* siteData = nil;
NSEnumerator* resultsEnum = [dataArray objectEnumerator];
while (siteData = [resultsEnum nextObject])
{
//
if( [[siteData objectForKey:#"Type"] isEqualToString: #"Banking"]) {
[bankingNotifications addObject:notification];
NSLog(#"Added object to banking array");
} else if ([[siteData objectForKey:#"Type"] isEqualToString: #"Fraud"])
{
[fraudNotifications addObject:notification];
NSLog(#"Added object to fraud array");
}
else if ([[siteData objectForKey:#"Type"] isEqualToString: #"Investment"])
{
[investmentNotifications addObject:notification];
NSLog(#"Added object to investment array");
}
}
}
The value for Key "aps" is a dictionary.
NSDictionary *item = [json valueForKeyPath:#"aps"];
if ([[item objectForKey:#"Type"] isEqualToString: #"Banking"])
{
[bankingNotifications addObject:notification];
NSLog(#"Added object to banking array");
}
else if ([[item objectForKey:#"Type"] isEqualToString: #"Fraud"])
{
[fraudNotifications addObject:notification];
NSLog(#"Added object to fraud array");
}
else if ([[item objectForKey:#"Type"] isEqualToString: #"Investment"])
{
[investmentNotifications addObject:notification];
NSLog(#"Added object to investment array");
}