I am new in iOS and I am facing problem regarding to get current value of string from array.
My code is like this
loginStatusHS = [[NSString alloc] initWithBytes: [myNSMDatalatetudeFromServer mutableBytes] length:[myNSMDatalatetudeFromServer length] encoding:NSUTF8StringEncoding];
NSLog(#"loginStatus =%#",loginStatusHS);
NSError *parseError = nil;
NSDictionary *xmlDictionary = [XMLReader dictionaryForXMLString:loginStatusHS error:&parseError];
NSLog(#"JSON DICTIONARY = %#",xmlDictionary);
recordResultHS = [xmlDictionary[#"success"] integerValue];
NSLog(#"Success: %ld",(long)recordResultHS);
NSDictionary* Address=[xmlDictionary objectForKey:#"soap:Envelope"];
NSLog(#"Address Dict = %#",Address);
NSDictionary *new =[Address objectForKey:#"soap:Body"];
NSLog(#"NEW DICT =%#",new);
NSDictionary *LoginResponse=[new objectForKey:#"HS_GetResponse"];
NSLog(#"Login Response DICT =%#",LoginResponse);
NSDictionary *LoginResult=[LoginResponse objectForKey:#"HS_GetResult"];
NSLog(#"Login Result =%#",LoginResult);
if(LoginResult.count>0)
{
NSLog(#"Login Result = %#",LoginResult);
NSLog(#"Login Result Dict =%#",LoginResult);
NSString *teststr =[[NSString alloc] init];
teststr =[LoginResult objectForKey:#"text"];
NSLog(#"Test String Value =%#",teststr);
NSString *string = [LoginResult valueForKey:#"text"];
NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
responseletetudedict = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSLog(#"Latetude Dictionary =%#",responseletetudedict);
idlatetudearray=[[NSMutableArray alloc]init];
idlatetudearray=[responseletetudedict valueForKey:#"City"];
NameHSArray=[[NSMutableArray alloc] init];
NameHSArray=[responseletetudedict valueForKey:#"Name"];
AddressHSArray=[[NSMutableArray alloc] init];
AddressHSArray=[responseletetudedict valueForKey:#"Address"];
FacilitiesHSArray=[[NSMutableArray alloc] init];
FacilitiesHSArray=[responseletetudedict valueForKey:#"Facilities"];
PhoneNoHSArray=[[NSMutableArray alloc] init];
PhoneNoHSArray=[responseletetudedict valueForKey:#"Phoneno"];
FaxnoHSArray=[[NSMutableArray alloc] init];
FaxnoHSArray=[responseletetudedict valueForKey:#"Faxno"];
LatitudeHSArray=[[NSMutableArray alloc] init];
LatitudeHSArray=[responseletetudedict valueForKey:#"Latitude"];
LongitudeHSArray=[[NSMutableArray alloc] init];
LongitudeHSArray=[responseletetudedict valueForKey:#"Longitude"];
TypeHSArray=[[NSMutableArray alloc] init];
TypeHSArray=[responseletetudedict valueForKey:#"Type"];
for (int i=0; i<NameHSArray.count; i++) {
double LatitudeDouble = [LatitudeHSArray[i] doubleValue];
double LongitudeDouble = [LongitudeHSArray[i] doubleValue];
CLLocationCoordinate2D position = CLLocationCoordinate2DMake(LatitudeDouble, LongitudeDouble);
GMSMarker *marker = [GMSMarker markerWithPosition:position];
marker.title = NameHSArray[i];
marker.snippet=AddressHSArray[i];
userData = [[NSArray alloc] initWithObjects:NameHSArray[i], AddressHSArray[i],FacilitiesHSArray[i], PhoneNoHSArray[i],FaxnoHSArray[i], TypeHSArray[i], nil];
marker.userData = userData;
if([TypeHSArray[i] isEqualToString:#"ESIC"])
{
marker.icon = [UIImage imageNamed:#"mapicon2.png"];
}
else
{
marker.icon = [UIImage imageNamed:#"mapicon1.png"];
}
GMSCameraUpdate *zoomCamera = [GMSCameraUpdate zoomIn];
[mapView animateWithCameraUpdate:zoomCamera];
marker.map = mapView;
}
Add in the Image when I click on Nobel Hospital I call the delegate
- (void)mapView:(GMSMapView *)mapView didTapInfoWindowOfMarker:(GMSMarker *)marker {
// your click action
StringAddress = marker.snippet;
StringName = marker.title;
NSLog(#"Address=%#",StringAddress);
NSLog(#"Name= %#",StringName);
lblNamepopup.text=StringName;
lblAddresspopup.text=StringAddress;
NSLog(#"User Data Array = %#",userData);
viewpopup.hidden=NO;
viewpopup.transform = CGAffineTransformMakeScale(0.01, 0.01);
[UIView animateWithDuration:0.2 delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{
viewpopup.transform = CGAffineTransformIdentity;
} completion:^(BOOL finished){
// do something once the animation finishes, put it here
}];
}
Hear in this delegate I need to get the current name of string address.But hear I am getting the Last value means the string get override. How can I get the value which I have click from array. Thanks in Advance!
You can get index as follow
-(void)mapView:(GMSMapView *)mapView didTapInfoWindowOfMarker:(GMSMarker *)marker
{
NSInteger index = [NameHSArray indexOfObject:marker.title];
NSLog(#"%ld",(long)index);
}
--- EDIT ---
You can also use
i found some reference from library.
Note that userData should not hold any strong references to any Maps
objects, otherwise a loop may be created (preventing ARC from releasing
objects).
NOTE :-
You can pass data through snippet but snippet show data into info window. so you creates a custom info window and show data as you want.
like this,
NSArray * userData = [NSArray alloc] initWithObjects:FacilitiesHSArray[i], PhoneNoHSArray[i],FaxnoHSArray[i], nil];
NSString *userDataString = [userData componentsJoinedByString:#";"];
marker.snippet = userDataString;
retrive
like this,
NSString *userDataString = marker.snippet;
NSArray *array = [userDataString componentsSeparatedByString:#";"];
NSLog(#"%#",array);
You can Do Like this
- (void)mapView:(GMSMapView *)mapView didTapInfoWindowOfMarker:(GMSMarker *)marker {
// your click action
StringAddress = marker.snippet;
StringName = marker.title;
NSInteger indexCheck = [NameHSArray indexOfObject:marker.title];
NSLog(#"Curret Index =%ld",(long)indexCheck);
StringName=[NSString stringWithFormat:#"%#",[NameHSArray objectAtIndex:indexCheck]];
StringAddress=[NSString stringWithFormat:#"%#",[AddressHSArray objectAtIndex:indexCheck]];
StringPhoneNo=[NSString stringWithFormat:#"%#",[PhoneNoHSArray objectAtIndex:indexCheck]];
NSLog(#"Address=%#",StringAddress);
NSLog(#"Name= %#",StringName);
NSLog(#"Phone No =%#",StringPhoneNo);
lblNamepopup.text=StringName;
lblAddresspopup.text=StringAddress;
}
Related
I'm using an NSDictionary to populate data for my MapView annotations. However, when I tap on my MapView annotation, the detailView should display the selected user's information. That said, right now, when I tap an annotation, all detailViews display the same user's information (even though the details in the actual annotation's display bubble are correct). How can I fix this? Why won't NSDictionary allow me to do this?
MapViewController.m
NSMutableDictionary *viewParams = [NSMutableDictionary new];
[viewParams setValue:#"u000" forKey:#"view_name"];
[DIOSView viewGet:viewParams success:^(AFHTTPRequestOperation *operation, id responseObject) {
self.addressData = [responseObject mutableCopy];
for (NSMutableDictionary *multiplelocations in self.addressData) {
NSString *location = multiplelocations[#"street_address"];
NSLog(#"Pull addresses %#", location);
NSString *userNames = multiplelocations[#"users_name"];
NSString *userBio = multiplelocations[#"userbio"];
CLGeocoder *geocoder = [[CLGeocoder alloc] init];
[geocoder geocodeAddressString:location
completionHandler:^(NSArray* placemarks, NSError* error){
if (placemarks && placemarks.count > 0) {
CLPlacemark *topResult = [placemarks objectAtIndex:0];
MKPlacemark *placemark = [[MKPlacemark alloc] initWithPlacemark:topResult];
MKCoordinateRegion region = self.mapView.region;
region.span.longitudeDelta /= 8.0;
region.span.latitudeDelta /= 8.0;
MKPointAnnotation *point = [[MKPointAnnotation alloc] init];
point.coordinate = placemark.coordinate;
point.title = userNames;
point.subtitle = userBio;
[self.mapView addAnnotation:point];
}
}
];
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Failure: %#", [error localizedDescription]);
}];
}
-(void)calloutTapped:(UITapGestureRecognizer *) sender
{
NSLog(#"Callout was tapped");
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:#"Main" bundle:nil];
OtherUserViewController *yourViewController = (OtherUserViewController *)[storyboard instantiateViewControllerWithIdentifier:#"OtherUserViewController"];
NSDictionary *dictionary = [[NSDictionary alloc] init];
dictionary = [[self.addressData firstObject] mutableCopy];
yourViewController.mapuserData = dictionary;
[self.navigationController pushViewController:yourViewController animated:YES];
}
self.addressData via console
{
address = "1300 Fake Street, Vancouver, BC";
childrenunder = No;
city = Va;
"emergency facility" = Yes;
"first name" = Admin;
"last name" = Account;
phone = "Not Available";
"photo_path" = "http://myurl.com/files/stored/1461176121.jpg";
"postal code" = V6B0L1;
"profile photo" = "<img typeof=\"foaf:Image\" src=\"stored/1461176121.jpg\" width=\"300\" height=\"300\" alt=\"\" />";
"property type" = House;
province = B;
"street_address" = "1300 Fake Street, Vancouver, BC";
supervision = Yes;
uid = 1;
userbio = "Need assistance? This account belongs to the team! Message us if you have any questions.";
"users_name" = Britt;
}
)
dictionary = [[self.addressData firstObject] mutableCopy];
Are you serious?
This should be
NSMutableDictionary *dictionary = [self.addressData mutableCopy];
While navigating to detail view controller, you are always getting the first object from the dictionary array.
[[self.addressData firstObject] mutableCopy];
Thats the reason you are getting the same information for all the annotation view.
Instead of that line of code, You have to identify which map marker is clicked on the MapView, for example identify the index of the dictionary array. Pick the dictionary from the array and pass it to the detail view.
I'm trying to pass data from an NSMutableArray to an NSDictionary. It seems I do this successfully, however XCode throws me a crash when trying to display the passed data in self.username.text. Any idea why this is and how I can fix it? See code below.
ViewController.m
-(void)calloutTapped:(UITapGestureRecognizer *) sender
{
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:#"Main" bundle:nil];
OtherUserViewController *yourViewController = (OtherUserViewController *)[storyboard instantiateViewControllerWithIdentifier:#"OtherUserViewController"];
NSDictionary *dictionary = [[NSDictionary alloc] init];
dictionary = [self.addressData mutableCopy];
yourViewController.mapuserData = dictionary;
[self.navigationController pushViewController:yourViewController animated:YES];
}
OtherUserViewController.m
- (void)viewDidLoad {
[super viewDidLoad];
if (self.mapuserData != NULL) {
NSLog(#"This is map user data %#", self.mapuserData);
self.addFriend.hidden = NO;
self.username.text = self.mapuserData[#"users_name"];
NSLog(#"THIS IS IT %#", self.mapuserData[#"users_name"]);
self.userBio.text = self.mapuserData[#"userbio"];
NSString *thirdLink = self.mapuserData[#"photo_path"];
NSString *ImageURLTwo = thirdLink;
NSData *imageDataTwo = [NSData dataWithContentsOfURL:[NSURL URLWithString:ImageURLTwo]];
self.userPhoto.image = [[UIImage alloc] initWithData:imageDataTwo];
}
if (neighbourDetail == NULL) {
self.addFriend.hidden = YES;
self.username.text = [self.myFriendData objectForKey:#"node_title"];
NSLog(#"this is friend detail %#", self.myFriendData);
self.userBio.text = [self.myFriendData objectForKey:#"body"];
NSString *thirdLink = [self.myFriendData objectForKey:#"friendphoto"];
NSString *ImageURLTwo = thirdLink;
NSData *imageDataTwo = [NSData dataWithContentsOfURL:[NSURL URLWithString:ImageURLTwo]];
self.userPhoto.image = [[UIImage alloc] initWithData:imageDataTwo];
} else {
self.addFriend.hidden = NO;
self.username.text = [neighbourDetail objectForKey:#"first name"];
NSLog(#"this is neighbour detail %#", neighbourDetail);
self.userBio.text = [neighbourDetail objectForKey:#"userbio"];
NSString *secondLink = [neighbourDetail objectForKey:#"photo_path"];
NSString *ImageURL = secondLink;
NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:ImageURL]];
self.userPhoto.image = [[UIImage alloc] initWithData:imageData];
}
NSString *testing = [self.myFriendData objectForKey:#"node_title"];
NSLog(#"This is the testing value %#", testing);
NSArray *friendorNo = self.checkfriendData;
NSLog(#"Friend or No Value %#", friendorNo);
for (NSDictionary *dict in friendorNo) {
if ([dict[#"node_title"] isEqualToString:testing]) {
self.addFriend.hidden = YES;
}
}
Logged data passed succesfully to self.mapuserData:
2017-06-14 22:03:49.397526-0700[3706:1178771] This is user data (
{
address = "2957 chill street";
childrenunder = Yes;
city = Vancouver;
"emergency facility" = None;
"first name" = josh;
"last name" = tree;
phone = 688;
"photo_path" = "x.png";
"points balance" = 24;
"postal code" = b6b6v5;
"profile photo" = "<null>";
"property type" = Apartment;
province = ont;
"special skills" = "None";
"star rating" = 0;
"street_address" = none;
supervision = Yes;
uid = 182;
userbio = nfkkdkckmfkekxkx;
"users_name" = "josh_tree#hotmail.com";
}
You are accessing an array.
Can you try this:
_username.text = [self.mapuserData firstObject][#"users_name"]
So, basically self.mapUserContent is an array of dictionary. What we did is get the first object and from the first object we get the username.
let me know if this works
You are trying to call objectForKey: for NSArray object.
self.addressData is a kind of NSArray
FIX:
NSDictionary *dictionary = [[NSDictionary alloc] init];
dictionary = [[self.addressData firstObject] mutableCopy];
yourViewController.mapuserData = dictionary;
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"];
}
I am trying to add pins from the server and show it one the map.
Normally I can show the pin but I want to add it online. I have three parsed json data NAME, Longitude and Latitude. I have parsed it in array. I couldn't know how to view it on the map
CLLocationCoordinate2D annotationCoord;
annotationCoord.latitude = 40.0000;
annotationCoord.longitude = 29.000;
MKPointAnnotation *annotationPoint = [[MKPointAnnotation alloc] init];
annotationPoint.coordinate = annotationCoord;
annotationPoint.title = name;
[self.locationMap addAnnotation:annotationPoint];
I have tried to add annotationCoord.latitude and annotationCoord.longitude in for loop but I get this error "bad receiver type 'CLLocationDegrees' (akadouble)" I think I am making big mistake but where I couldn't know. Please need help.
- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation{
for (int i = 0; i < jsonArray.count; i++) {
NSString *lat = [jsonArray objectAtIndex:i];
[annotationCoord.latitude addObject:lat];
}
}
My JSON return:
response = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:#"http://kalkatawi.com/mapLocation.php"]];
NSError *parseError = nil;
jsonArray = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingAllowFragments error:&parseError];
jsonArray1 = [[NSMutableArray alloc] init];
jsonArray2 = [[NSMutableArray alloc] init];
jsonArray3 = [[NSMutableArray alloc] init];
for(int i=0;i<[jsonArray count];i++)
{
name = [[jsonArray objectAtIndex:i] objectForKey:#"name"];
[jsonArray1 addObject:name];
}
for(int i=0;i<[jsonArray count];i++)
{
longitude = [[jsonArray objectAtIndex:i] objectForKey:#"longitude"];
[jsonArray2 addObject:longitude];
}
for(int i=0;i<[jsonArray count];i++)
{
latitude = [[jsonArray objectAtIndex:i] objectForKey:#"latitude"];
[jsonArray3 addObject:latitude];
}
self.locationMap.delegate = self;
Based on the updated code, jsonArray already is an array of dictionaries with each dictionary holding the properties of each annotation.
I don't understand why you want to split that up into three separate arrays (one for each property).
Why not use jsonArray as-is to create the annotations:
jsonArray = [NSJSONSerialization JSONObjectWithData:...
self.locationMap.delegate = self; //set delegate before adding annotations
for (int i=0; i < [jsonArray count]; i++)
{
NSDictionary *annotationDictionary = [jsonArray objectAtIndex:i];
name = [annotationDictionary objectForKey:#"name"];
annotationCoord.latitude
= [[annotationDictionary objectForKey:#"latitude"] doubleValue];
annotationCoord.longitude
= [[annotationDictionary objectForKey:#"longitude"] doubleValue];
MKPointAnnotation *annotationPoint = [[MKPointAnnotation alloc] init];
annotationPoint.coordinate = annotationCoord;
annotationPoint.title = name;
[self.locationMap addAnnotation:annotationPoint];
}
The updated code in the question also shows it looping through jsonArray in the didUpdateUserLocation delegate method. It's not clear why this is being done in that delegate method but if you're planning to update the annotations on the map every time the user moves, you may also need to remove all/some existing annotations before adding again to avoid duplicate annotations.
Try
- (void)addAnnotations:(NSArray *)annotations;
of MKMApView
The explanation given in top answer. I only convert this code into Swift 3.
Swift 3
jsonArray = JSONSerialization.jsonObjectWithData()
locationMap.delegate = self
for i in 0..<jsonArray.count() {
var annotationDictionary = jsonArray[i]
name = annotationDictionary["name"]
annotationCoord.latitude = annotationDictionary["latitude"]!
annotationCoord.longitude = annotationDictionary["longitude"]!
var annotationPoint = MKPointAnnotation()
annotationPoint.coordinate = annotationCoord
annotationPoint.title = name
locationMap.addAnnotation(annotationPoint)
}
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");
}