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];
Related
I have create a demo for downloading a file from the server it is working fine with foreground and background, but when I'm going to resume it, It will giving below Error
I have stcuk here could help me so solved it, I search in internet but I couldn't find anything helpful.
Download file and Pause Downlaod is working fine I have issue to resume it.
Task <3AE5BF24-3A4E-4713-8FC2-A0032022C913>.<6> finished with error [-3003] Error Domain=NSURLErrorDomain Code=-3003 "(null)" UserInfo={_NSURLErrorRelatedURLSessionTaskErrorKey=(
"BackgroundDownloadTask <3AE5BF24-3A4E-4713-8FC2-A0032022C913>.<6>"
), _NSURLErrorFailingURLSessionTaskErrorKey=BackgroundDownloadTask <3AE5BF24-3A4E-4713-8FC2-A0032022C913>.<6>}
Here is the final Xcode project
Downlaod xcode project
#import "NSURLSession+ResumeData.h"
#import <UIKit/UIKit.h>
#define IS_IOS10ORLATER ([[[UIDevice currentDevice] systemVersion] floatValue] >= 10)
#pragma mark- private
static NSData * correctRequestData(NSData *data) {
if (!data) {
return nil;
}
// return the same data if it's correct
if ([NSKeyedUnarchiver unarchiveObjectWithData:data] != nil) {
return data;
}
NSMutableDictionary *archive = [[NSPropertyListSerialization propertyListWithData:data options:NSPropertyListMutableContainersAndLeaves format:nil error:nil] mutableCopy];
if (!archive) {
return nil;
}
NSInteger k = 0;
id objectss = archive[#"$objects"];
while ([objectss[1] objectForKey:[NSString stringWithFormat:#"$%ld",k]] != nil) {
k += 1;
}
NSInteger i = 0;
while ([archive[#"$objects"][1] objectForKey:[NSString stringWithFormat:#"__nsurlrequest_proto_prop_obj_%ld",i]] != nil) {
NSMutableArray *arr = archive[#"$objects"];
NSMutableDictionary *dic = arr[1];
id obj = [dic objectForKey:[NSString stringWithFormat:#"__nsurlrequest_proto_prop_obj_%ld",i]];
if (obj) {
[dic setValue:obj forKey:[NSString stringWithFormat:#"$%ld",i+k]];
[dic removeObjectForKey:[NSString stringWithFormat:#"__nsurlrequest_proto_prop_obj_%ld",i]];
[arr replaceObjectAtIndex:1 withObject:dic];
archive[#"$objects"] = arr;
}
i++;
}
if ([archive[#"$objects"][1] objectForKey:#"__nsurlrequest_proto_props"] != nil) {
NSMutableArray *arr = archive[#"$objects"];
NSMutableDictionary *dic = arr[1];
id obj = [dic objectForKey:#"__nsurlrequest_proto_props"];
if (obj) {
[dic setValue:obj forKey:[NSString stringWithFormat:#"$%ld",i+k]];
[dic removeObjectForKey:#"__nsurlrequest_proto_props"];
[arr replaceObjectAtIndex:1 withObject:dic];
archive[#"$objects"] = arr;
}
}
// Rectify weird "NSKeyedArchiveRootObjectKey" top key to NSKeyedArchiveRootObjectKey = "root"
if ([archive[#"$top"] objectForKey:#"NSKeyedArchiveRootObjectKey"] != nil) {
[archive[#"$top"] setObject:archive[#"$top"][#"NSKeyedArchiveRootObjectKey"] forKey: NSKeyedArchiveRootObjectKey];
[archive[#"$top"] removeObjectForKey:#"NSKeyedArchiveRootObjectKey"];
}
// Reencode archived object
NSData *result = [NSPropertyListSerialization dataWithPropertyList:archive format:NSPropertyListBinaryFormat_v1_0 options:0 error:nil];
return result;
}
static NSMutableDictionary *getResumeDictionary(NSData *data) {
NSMutableDictionary *iresumeDictionary = nil;
if (IS_IOS10ORLATER) {
id root = nil;
id keyedUnarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
#try {
root = [keyedUnarchiver decodeTopLevelObjectForKey:#"NSKeyedArchiveRootObjectKey" error:nil];
if (root == nil) {
root = [keyedUnarchiver decodeTopLevelObjectForKey:NSKeyedArchiveRootObjectKey error:nil];
}
} #catch(NSException *exception) {
}
[keyedUnarchiver finishDecoding];
iresumeDictionary = [root mutableCopy];
}
if (iresumeDictionary == nil) {
iresumeDictionary = [NSPropertyListSerialization propertyListWithData:data options:NSPropertyListMutableContainersAndLeaves format:nil error:nil];
}
return iresumeDictionary;
}
static NSData *correctResumeData(NSData *data) {
NSString *kResumeCurrentRequest = #"NSURLSessionResumeCurrentRequest";
NSString *kResumeOriginalRequest = #"NSURLSessionResumeOriginalRequest";
if (data == nil) {
return nil;
}
NSMutableDictionary *resumeDictionary = getResumeDictionary(data);
if (resumeDictionary == nil) {
return nil;
}
resumeDictionary[kResumeCurrentRequest] = correctRequestData(resumeDictionary[kResumeCurrentRequest]);
resumeDictionary[kResumeOriginalRequest] = correctRequestData(resumeDictionary[kResumeOriginalRequest]);
NSData *result = [NSPropertyListSerialization dataWithPropertyList:resumeDictionary format:NSPropertyListXMLFormat_v1_0 options:0 error:nil];
return result;
}
#implementation NSURLSession (ResumeData)
- (NSURLSessionDownloadTask *)downloadTaskWithCorrectResumeData:(NSData *)resumeData {
NSString *kResumeCurrentRequest = #"NSURLSessionResumeCurrentRequest";
NSString *kResumeOriginalRequest = #"NSURLSessionResumeOriginalRequest";
NSData *cData = correctResumeData(resumeData);
cData = cData ? cData:resumeData;
NSURLSessionDownloadTask *task = [self downloadTaskWithResumeData:cData];
NSMutableDictionary *resumeDic = getResumeDictionary(cData);
if (resumeDic) {
if (task.originalRequest == nil) {
NSData *originalReqData = resumeDic[kResumeOriginalRequest];
NSURLRequest *originalRequest = [NSKeyedUnarchiver unarchiveObjectWithData:originalReqData ];
if (originalRequest) {
[task setValue:originalRequest forKey:#"originalRequest"];
}
}
if (task.currentRequest == nil) {
NSData *currentReqData = resumeDic[kResumeCurrentRequest];
NSURLRequest *currentRequest = [NSKeyedUnarchiver unarchiveObjectWithData:currentReqData];
if (currentRequest) {
[task setValue:currentRequest forKey:#"currentRequest"];
}
}
}
return task;
}
#end
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 using REST API to fetch data. I have two methods, one for ResponceSucces and other for responceFailure. In responce failure I simply dismiss the activity indicator. Sometimes it happens that data is not retrieved but still activity indicator keeps spinning infinitely. And ResponceFailure method is not Called.
My question is can I set timeout interval to my web service, to check if response did not come, then activity indicator must be dismissed after some time for example 20/30 seconds.
Below is my code:
-(void)messagesGetSuccess:(FBListingsWebHandler*)handler response:(NSDictionary*)response
{
[MBProgressHUD hideHUDForView:self.view animated:YES];
[[FBModelManager sharedModelManager].messages removeAllObjects];
NSArray *messagesArray = [response objectForKey:#"message"];
if([[FBUserManager sharedUserManager] userType] == kUserShipper){
//extract usernames of transporters who placed bid on selected listing
NSArray *userNames;
NSMutableArray *transporterNames;
NSDictionary *biddingsDic = [[FBModelManager sharedModelManager] getModelDictionary:kModelBiddings];
if ([biddingsDic count] > 0){
userNames = [[biddingsDic allValues] valueForKey:#"userName"];
NSOrderedSet *orderedSet = [NSOrderedSet orderedSetWithArray:userNames];
NSSet *uniqueNames = [orderedSet set];
transporterNames = [[NSMutableArray alloc] initWithArray:[uniqueNames allObjects]];
}
//add transporter records in messages dictionary who have messages for selected listing
for (int i = 1; i < [messagesArray count]; i++) {
NSMutableArray *modelArray = [[NSMutableArray alloc] init];
NSDictionary *groupedMsgDic = [messagesArray objectAtIndex:i];
int count = (int)[[[groupedMsgDic allValues] objectAtIndex:0] count];
for (int j = 0; j < count; j++) {
FBMessagesModel *model = [[FBMessagesModel alloc] initWithMessageItems:[[[groupedMsgDic allValues] objectAtIndex:0] objectAtIndex:j]];
[modelArray addObject:model];
model = nil;
}
[[FBModelManager sharedModelManager].messages setObject:modelArray forKey:[[groupedMsgDic allKeys] objectAtIndex:0]];
//remove transporter usernames from array who have messages besides bid for selected listing
if([transporterNames containsObject:[[groupedMsgDic allKeys] objectAtIndex:0]]){
[transporterNames removeObject:[[groupedMsgDic allKeys] objectAtIndex:0]];
}
modelArray = nil;
}
//add transporter records in messages dictionary who placed bid but have no message for selected listing
for (int i = 0; i < [transporterNames count]; i++) {
NSString *path = [[[biddingsDic allValues] objectAtIndex:[userNames indexOfObject:[transporterNames objectAtIndex:i]]] photoPath];
int transporterId = [[[biddingsDic allValues] objectAtIndex:[userNames indexOfObject:[transporterNames objectAtIndex:i]]] userId];
NSString *objectForZeroMsgs = [NSString stringWithFormat:#"%#-%d",path,transporterId];
[[FBModelManager sharedModelManager].messages setObject:objectForZeroMsgs forKey:[transporterNames objectAtIndex:i]];
}
transporterNames = nil;
// [self tableView:self.shipperGroupedMessagesTableView_ numberOfRowsInSection:0];
[self.shipperGroupedMessagesTableView_ reloadData];
}else if([[FBUserManager sharedUserManager] userType] == kUserTransporter){
for (int i = 1; i < [messagesArray count]; i++) {
FBMessagesModel *model = [[FBMessagesModel alloc] initWithMessageItems:[messagesArray objectAtIndex:i]];
[[FBModelManager sharedModelManager].messages setObject:model forKey:[NSString stringWithFormat:#"%d",model.mailId]];
if(model.mailMessage && ![model.mailMessage isEqualToString:#""]){
[self createMessageBubble:model];
}
model = nil;
}
[self.bubbleTableView_ reloadData];
}
}
-(void)messagesGetFailure:(FBListingsWebHandler*)handler
{
[MBProgressHUD hideHUDForView:self.view animated:YES];
[[FBModelManager sharedModelManager].messages removeAllObjects];
if([[FBUserManager sharedUserManager] userType] == kUserTransporter){
[self.bubbleTableView_ reloadData];
}
else if([[FBUserManager sharedUserManager] userType] == kUserShipper){
if([[FBModelManager sharedModelManager].messages count] == 0){
NSDictionary *biddingsDic = [[FBModelManager sharedModelManager] getModelDictionary:kModelBiddings];
if ([biddingsDic count] > 0){
NSArray *userNames = [[biddingsDic allValues] valueForKey:#"userName"];
NSOrderedSet *orderedSet = [NSOrderedSet orderedSetWithArray:userNames];
NSSet *uniqueNames = [orderedSet set];
NSArray *transporterNames = [uniqueNames allObjects];
[[FBModelManager sharedModelManager].messages removeAllObjects];
for (int i = 0; i < [transporterNames count]; i++) {
NSString *path = [[[biddingsDic allValues] objectAtIndex:[userNames indexOfObject:[transporterNames objectAtIndex:i]]] photoPath];
int transporterId = [[[biddingsDic allValues] objectAtIndex:[userNames indexOfObject:[transporterNames objectAtIndex:i]]] userId];
NSString *objectForZeroMsgs = [NSString stringWithFormat:#"%#-%d",path,transporterId];
[[FBModelManager sharedModelManager].messages setObject:objectForZeroMsgs forKey:[transporterNames objectAtIndex:i]];
}
[self.shipperGroupedMessagesTableView_ reloadData];
}else{
[self addNoMessagesLabel];
}
}
[self.shipperGroupedMessagesTableView_ reloadData];
}
}
I am adding a screenshot.
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");
}