ios: how to populate mapview from .plist file - ios

Hello and Thanks for the help.
Is it possible to populate 10 mapview locations from a .plist file using a for loop ? If so how ?
my current code for my mapview is all hard coded. I would like to improve upon this by pulling - Longitude, Latitude, Title, SubTitle - from a for loop if possible. Thank You.
////
.....
MKCoordinateRegion region3 = {{0.0,0.0}, {0.0,0.0}};
region3.center.latitude = 33.45869;
region3.center.longitude = -84.66931;
region3.span.longitudeDelta = 0.01f;
region3.span.latitudeDelta=0.01f;
// [mapview setRegion:region4 animated:YES];
BandsMap *ann3 = [[BandsMap alloc]init];
ann3.title = #"Indigo Bar & Lounge";
ann3.subtitle = #"Let the good times roll";
ann3.coordinate = region3.center;//
////
annoArray = [[NSArray alloc] initWithObjects:ann1,ann2,ann3.....,nil];
[mapView addAnnotations:annoArray];.......
Something like this I suppose but not quite sure how to finish
for(NSDictionary *key in mapDataPlist)
{
NSString *c = [key objectForKey:#"Title"];
NSString *a = [key objectForKey:#"SubTitle"];
NSString *lat = [key objectForKey:#"Latitude"];
NSString *lon = [key objectForKey:#"Longitude"];
CGFloat strFLat = (CGFloat)[lat floatValue];
CGFloat strFLon = (CGFloat)[lon floatValue];
//////
?????
}

Just iterate over your plist array and use the code you have to create the regions from the extracted data. Then, instead of annoArray being an array you create at the end, make it a mutable array and add each item at the end of each loop iteration.

[mapView setRegion:adjustedRegion animated:YES];
mapView.mapType=MKMapTypeStandard;
UITableView *tableView = [[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame] style:UITableViewStylePlain];
tableView.dataSource = self;
tableView.delegate = self;
tableView.frame = CGRectMake(28, 60, 334, 649);
[self.view addSubview:tableView];
NSString *path = [[NSBundle mainBundle] pathForResource:
#"CityList" ofType:#"plist"];
NSMutableArray *cities = [[NSMutableArray alloc] initWithContentsOfFile:path];
NSMutableArray *localCities= [[NSMutableArray alloc]init];
for (int i=0;i<[cities count];i++)
{
NSLog(#"%#",[[cities objectAtIndex:i]objectForKey:#"cityNameKey"]);
[localCities addObject:[[cities objectAtIndex:i]objectForKey:#"cityNameKey"]];
}
locationArray= localCities;
Annotation *annotation=[[Annotation alloc]init];
annotation.coordinate = CLLocationCoordinate2DMake(29.7631,-95.3631);
annotation.color = [UIColor redColor];
annotation.title=[NSString stringWithFormat:#"Houston"];
[mapView addAnnotation:annotation];

Related

Objective C - Convert DMS to LAT LONG (South and East)

Heads up, I'm an absolute newb when it comes to OBJ-C!
I'm currently putting together and IOS app and utilising pre-loaded data listings/locations from my client. The coordinates to each listing/location has are in DMS, eg
S:35 00.065
E:148 06.660
There are thousands of listings and I can't go and change this over for each one. I'm currently importing that data via a WordPress JSON API (WP REST API Plugin). The app I'm making pulls that JSON data in and populates accordingly.
The format is simply 'east' and south' from the JSON URL.
http://example.com/api/get_recent_posts/?custom_fields=name,east,south,image,address,type,Postend&page=%ld
I have no idea how to convert the east and south into lat and long for the code. Everything is ready to go except this predicament!
Everything I find on here leads to expired or dead links for their respective tutorials, in Javascript, PHP, or is reversing LAT LONG to DMS. :(
Thanks in advance!
--- EDIT WITH POSSIBLE ANSWER ---
Thanks to #ronak-chaniyara for the answer. Just having troubles implementing into current code. Existing code from template below:
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
NSString *decodedText1 = [_restaurant.name stringByReplacingOccurrencesOfString:#"’" withString:#"'"];
NSString *decodedText = [decodedText1
stringByReplacingOccurrencesOfString:#"&" withString:#"&"];
self.title = _restaurant.type;
self.barname.text = decodedText;
self.address.text = _restaurant.location;
[[self navigationController] setNavigationBarHidden:NO animated:NO];
[self loadImageInNewThread];
NSString *htmlFile = [[NSBundle mainBundle] pathForResource:#"ht7" ofType:#"html"];
NSString* htmlString = [NSString stringWithContentsOfFile:htmlFile encoding:NSUTF8StringEncoding error:nil];
NSString *htmlString2 = [NSString stringWithFormat:htmlString,_restaurant.description];
self.webView.delegate=self;
[self.webView loadHTMLString:htmlString2 baseURL:nil];
_webView.opaque = NO;
_webView.backgroundColor = [UIColor clearColor];
self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:0.306 green:0.306 blue:0.306 alpha:1];
self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
[self.navigationController.navigationBar
setTitleTextAttributes:#{NSForegroundColorAttributeName : [UIColor whiteColor]}];
self.navigationController.navigationBar.translucent = NO;
self.EntityPlot.delegate = self;
CLLocationCoordinate2D coordinate1 = CLLocationCoordinate2DMake(_restaurant.lattitude, _restaurant.longditude);
EntityPlot *coordinate2 = [[EntityPlot alloc] initWithTitle:decodedText Location:coordinate1];
[self.EntityPlot addAnnotation: coordinate2];
CLLocationCoordinate2D annotationCoord;
annotationCoord.latitude = _restaurant.lattitude;
annotationCoord.longitude = _restaurant.longditude;
UIImage *image = [UIImage imageNamed:#"cream_pixels_#2X.png"];
self.uiView.backgroundColor = [UIColor colorWithPatternImage:image];
[_barplot setRegion:MKCoordinateRegionMake(annotationCoord, MKCoordinateSpanMake(.005, .005)) animated:YES];
[_barplot selectAnnotation:coordinate2 animated:YES];
_barplot.showsUserLocation = YES;
Me trying to implement:
//Pass string DMS for Lat and Long
- (double)DMSStringToDecimal:(NSString*)strDMS
{
// split the string
NSArray *arrSplit = [strDMS componentsSeparatedByString:#":"];
//direction
NSString *direction = [arrSplit objectAtIndex:0];
//degree
NSString *degreesString = [[[arrSplit objectAtIndex:1] componentsSeparatedByString:#" "] objectAtIndex:0];
NSArray *arrMinuteandSeconds=[[[[arrSplit objectAtIndex:1] componentsSeparatedByString:#" "] objectAtIndex:1] componentsSeparatedByString:#"."];
//minutes
NSString *minutesString = [arrMinuteandSeconds objectAtIndex:0];
//seconds
NSString *secondsString = [arrMinuteandSeconds objectAtIndex:1];
// convert degrees
double degrees = [degreesString doubleValue];
// convert minutes
double minutes = [minutesString doubleValue] / 60; // 60 degrees in a minute
// convert seconds
double seconds = [secondsString doubleValue] / 3600; // 60 seconds in a minute, or 3600 in a degree
// add them all together
double decimal = degrees + minutes + seconds;
// determine if this is negative. south and west would be negative values
if ([direction.uppercaseString isEqualToString:#"W"] || [direction.uppercaseString isEqualToString:#"S"])
{
decimal = -decimal;
}
return decimal;
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
NSString *decodedText1 = [_restaurant.name stringByReplacingOccurrencesOfString:#"’" withString:#"'"];
NSString *decodedText = [decodedText1
stringByReplacingOccurrencesOfString:#"&" withString:#"&"];
self.title = _restaurant.type;
self.barname.text = decodedText;
self.address.text = _restaurant.location;
[[self navigationController] setNavigationBarHidden:NO animated:NO];
[self loadImageInNewThread];
NSString *htmlFile = [[NSBundle mainBundle] pathForResource:#"ht7" ofType:#"html"];
NSString* htmlString = [NSString stringWithContentsOfFile:htmlFile encoding:NSUTF8StringEncoding error:nil];
NSString *htmlString2 = [NSString stringWithFormat:htmlString,_restaurant.description];
self.webView.delegate=self;
[self.webView loadHTMLString:htmlString2 baseURL:nil];
_webView.opaque = NO;
_webView.backgroundColor = [UIColor clearColor];
self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:0.306 green:0.306 blue:0.306 alpha:1];
self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
[self.navigationController.navigationBar
setTitleTextAttributes:#{NSForegroundColorAttributeName : [UIColor whiteColor]}];
self.navigationController.navigationBar.translucent = NO;
self.EntityPlot.delegate = self;
// location crap
NSString *latStr = [NSString stringWithFormat:htmlString,_restaurant.lattitude];
NSString *lonStr = [NSString stringWithFormat:htmlString,_restaurant.longditude];
double lat = [self DMSStringToDecimal:latStr]; //which gives lat=-35.018055555555556
double lon = [self DMSStringToDecimal:lonStr]; //which gives lon=148.28333333333333
// CLLocation *loc = [[CLLocation alloc] initWithLatitude:lat longitude:lon];
CLLocationCoordinate2D coordinate1 = CLLocationCoordinate2DMake(lat, lon);
EntityPlot *coordinate2 = [[EntityPlot alloc] initWithTitle:decodedText Location:coordinate1];
// CLLocationCoordinate2D coordinate1 = CLLocationCoordinate2DMake(_restaurant.lattitude, _restaurant.longditude);
// EntityPlot *coordinate2 = [[EntityPlot alloc] initWithTitle:decodedText Location:coordinate1];
[self.EntityPlot addAnnotation: coordinate2];
CLLocationCoordinate2D annotationCoord;
annotationCoord.latitude = lat;
annotationCoord.longitude = lon;
// annotationCoord.latitude = _restaurant.lattitude;
// annotationCoord.longitude = _restaurant.longditude;
UIImage *image = [UIImage imageNamed:#"cream_pixels_#2X.png"];
self.uiView.backgroundColor = [UIColor colorWithPatternImage:image];
[_barplot setRegion:MKCoordinateRegionMake(annotationCoord, MKCoordinateSpanMake(.005, .005)) animated:YES];
[_barplot selectAnnotation:coordinate2 animated:YES];
_barplot.showsUserLocation = YES;
}
May be you can do something like below, (from answer: https://stackoverflow.com/a/28545279/5575752):
NSString *latStr=#"S:35 00.065";
NSString *lonStr=#"E:148 06.660";
double lat = [self DMSStringToDecimal:latStr]; //which gives lat=-35.018055555555556
double lon = [self DMSStringToDecimal:lonStr]; //which gives lon=148.28333333333333
// Now create Location object
CLLocation *loc = [[CLLocation alloc] initWithLatitude:lat longitude:lon];
//Pass string DMS for Lat and Long
- (double)DMSStringToDecimal:(NSString*)strDMS
{
// split the string
NSArray *arrSplit = [strDMS componentsSeparatedByString:#":"];
//direction
NSString *direction = [arrSplit objectAtIndex:0];
//degree
NSString *degreesString = [[[arrSplit objectAtIndex:1] componentsSeparatedByString:#" "] objectAtIndex:0];
NSArray *arrMinuteandSeconds=[[[[arrSplit objectAtIndex:1] componentsSeparatedByString:#" "] objectAtIndex:1] componentsSeparatedByString:#"."];
//minutes
NSString *minutesString = [arrMinuteandSeconds objectAtIndex:0];
//seconds
NSString *secondsString = [arrMinuteandSeconds objectAtIndex:1];
// convert degrees
double degrees = [degreesString doubleValue];
// convert minutes
double minutes = [minutesString doubleValue] / 60; // 60 degrees in a minute
// convert seconds
double seconds = [secondsString doubleValue] / 3600; // 60 seconds in a minute, or 3600 in a degree
// add them all together
double decimal = degrees + minutes + seconds;
// determine if this is negative. south and west would be negative values
if ([direction.uppercaseString isEqualToString:#"W"] || [direction.uppercaseString isEqualToString:#"S"])
{
decimal = -decimal;
}
return decimal;
}
Do modifications as per your requirement.
Hope it will help:)

Sorting an array for UITableView

I have a function which prepares data for my UITableView:
- (void) SearchFromMyPosition {
TitleLabelSort = [[NSMutableArray alloc] init];
DistanceLabelSort = [[NSMutableArray alloc] init];
TagValueSort = [[NSMutableArray alloc] init];
DistanceUnitSort = [[NSMutableArray alloc] init];
LatArraySort = [[NSMutableArray alloc] init];
LngArraySort = [[NSMutableArray alloc] init];
// loading
[activityIndicatorObject startAnimating];
NSNumber *latNr1 = [[NSUserDefaults standardUserDefaults] valueForKey:#"api_lat"];
NSNumber *lngNr1 = [[NSUserDefaults standardUserDefaults] valueForKey:#"api_lng"];
double lat1 = [latNr1 doubleValue];
double lng1 = [lngNr1 doubleValue];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSArray *array = [APIConnection GetDataFromUrlAuth];
dispatch_async(dispatch_get_main_queue(), ^{
for (NSString *item in array) {
NSArray *coords = [[[array valueForKey:item] valueForKey:#"location"] componentsSeparatedByString:#"|"];
double lat2 = [[coords objectAtIndex:0] doubleValue];
double lng2 = [[coords objectAtIndex:1] doubleValue];
CLLocation *oldLocation = [[CLLocation alloc] initWithLatitude:lat1 longitude:lng1];
CLLocation *newLocation = [[CLLocation alloc] initWithLatitude:lat2 longitude:lng2];
CLLocationDistance meters = [newLocation distanceFromLocation:oldLocation];
[LatArraySort addObject:[NSString stringWithFormat:#"%f",lat2]];
[LngArraySort addObject:[NSString stringWithFormat:#"%f",lng2]];
[TitleLabelSort addObject:[[array valueForKey:item] valueForKey:#"name"]];
[DistanceLabelSort addObject:[NSString stringWithFormat:#"%f",meters]];
[TagValueSort addObject:item];
[self.myTableView reloadData];
[activityIndicatorObject stopAnimating];
}
});
});
}
This works but I need to sort results by DistanceLabelSort
For sorting CoreData results I use below function and works fine:
- (void) SetTableData {
TitleLabel = [[NSMutableArray alloc] init];
DistanceLabel = [[NSMutableArray alloc] init];
TagValue = [[NSMutableArray alloc] init];
DistanceUnit = [[NSMutableArray alloc] init];
LatArray = [[NSMutableArray alloc] init];
LngArray = [[NSMutableArray alloc] init];
// sorting
NSArray *sortedArray = [DistanceLabelSort sortedArrayUsingComparator:^(NSString *str1, NSString *str2) {
return [str1 compare:str2 options:NSNumericSearch];
}];
NSString *sortIdentStr = [[NSString alloc] init];
unsigned long sortIdent;
NSMutableArray *arrayUnit = [[NSMutableArray alloc] init];
for (int i = 0; i < sortedArray.count; i++) {
sortIdentStr = [sortedArray objectAtIndex:i];
sortIdent = [DistanceLabel indexOfObject:sortIdentStr];
arrayUnit = [self unitStr:sortIdentStr];
[TitleLabel addObject:[TitleLabelSort objectAtIndex:sortIdent]];
[TagValue addObject:[TagValueSort objectAtIndex:sortIdent]];
[LatArray addObject:[LatArraySort objectAtIndex:sortIdent]];
[LngArray addObject:[LngArraySort objectAtIndex:sortIdent]];
[DistanceLabel addObject:[arrayUnit objectAtIndex:0]];
[DistanceUnit addObject:[arrayUnit objectAtIndex:1]];
[self.myTableView reloadData];
[activityIndicatorObject stopAnimating];
}
}
But if I try use this for sorting data from external api function SetTableData is done before I get results from external api.
Finally I found solution and maybe this will be helpful for others:
I added function which checks if the task is done:
- (void)SearchFromMyPositionWithSuccess:(void (^)(void))successHandler failure:(void (^)(void))failureHandler {
TitleLabelSort = [[NSMutableArray alloc] init];
DistanceLabelSort = [[NSMutableArray alloc] init];
TagValueSort = [[NSMutableArray alloc] init];
DistanceUnitSort = [[NSMutableArray alloc] init];
LatArraySort = [[NSMutableArray alloc] init];
LngArraySort = [[NSMutableArray alloc] init];
// loading
[activityIndicatorObject startAnimating];
NSNumber *latNr1 = [[NSUserDefaults standardUserDefaults] valueForKey:#"api_lat"];
NSNumber *lngNr1 = [[NSUserDefaults standardUserDefaults] valueForKey:#"api_lng"];
double lat1 = [latNr1 doubleValue];
double lng1 = [lngNr1 doubleValue];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSArray *array = [APIConnection GetDataFromUrlAuth];
dispatch_async(dispatch_get_main_queue(), ^{
int i = 0;
for (NSString *item in array) {
i++;
NSArray *coords = [[[array valueForKey:item] valueForKey:#"location"] componentsSeparatedByString:#"|"];
double lat2 = [[coords objectAtIndex:0] doubleValue];
double lng2 = [[coords objectAtIndex:1] doubleValue];
CLLocation *oldLocation = [[CLLocation alloc] initWithLatitude:lat1 longitude:lng1];
CLLocation *newLocation = [[CLLocation alloc] initWithLatitude:lat2 longitude:lng2];
CLLocationDistance meters = [newLocation distanceFromLocation:oldLocation];
[LatArraySort addObject:[NSString stringWithFormat:#"%f",lat2]];
[LngArraySort addObject:[NSString stringWithFormat:#"%f",lng2]];
[TitleLabelSort addObject:[[array valueForKey:item] valueForKey:#"name"]];
[DistanceLabelSort addObject:[NSString stringWithFormat:#"%f",meters]];
[TagValueSort addObject:item];
if (i == array.count) {
successHandler();
}
[activityIndicatorObject stopAnimating];
}
});
});
}
And wait for success in this function:
-(void) SearchFromMyPosition {
[self SearchFromMyPositionWithSuccess: ^{
[self SetTableData];
NSLog(#"success");
} failure:^{
NSLog(#"failure");
}];
}
This solves my case :)

Map Annotations Displayed on Date

I have a map that displays an array of annotations. These annotations are all called from a plist and each have a date at which they occur. I would like these annotations to display only on the date that they happen, however I have no clue how to approach this. Any help would be much appreciated.
for (NSString *dateString in contentArray) {
[[NSUserDefaults standardUserDefaults] stringForKey:#"Date"];
}
This is the little bit of code I have written in but it does not solve anything for me.
EDIT:
Here is the code that calls the annotations generally.
-(void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
self.navigationController.navigationBarHidden = YES;
indexValue = 0;
NSString* plistPath = [[NSBundle mainBundle] pathForResource:#"mapAddress" ofType:#"plist"];
NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithContentsOfFile:plistPath];
NSString *strID = [NSString stringWithFormat:#"%d",intID];
NSLog(#"array : %#",[dict objectForKey:strID]);
[contentArray removeAllObjects];
[contentArray addObjectsFromArray:[dict objectForKey:strID]];
[contentArray retain];
[self zoomToUserLocation:mapViewuno.userLocation];
}
- (void)zoomToUserLocation:(MKUserLocation *)userLocation
{
if (!userLocation)
return;
MKCoordinateRegion region;
region.center = userLocation.location.coordinate;
region.span = MKCoordinateSpanMake(.5, .5);
region = [mapViewuno regionThatFits:region];
[mapViewuno setRegion:region animated:YES];
counter = 0;
[mapViewuno removeAnnotations:mapViewuno.annotations];
if([contentArray count] != 0)
{
for(indexValue = 0; indexValue<[contentArray count];indexValue++)
{
FirstAnnotation *obj=[[FirstAnnotation alloc]init];
obj.latitude = [[[contentArray objectAtIndex:indexValue] objectForKey:#"lattitude"] floatValue];
obj.longitude = [[[contentArray objectAtIndex:indexValue] objectForKey:#"Longitude"] floatValue];
obj.titleName=[[contentArray objectAtIndex:indexValue] objectForKey:#"Title"];
obj.Address = [[contentArray objectAtIndex:indexValue] objectForKey:#"Address"];
obj.Phone = [[contentArray objectAtIndex:indexValue] objectForKey:#"Phone"];
obj.intTag = indexValue;
[mapViewuno addAnnotation:obj];
}
if ([mapViewuno.annotations count] == 0) return;
// [self.mapView setRegion:newRegion animated:YES];
}
}

How to add multiple pins/annotation online?

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)
}

New PList Retrieval Code Prevents MKMapView Delegate Method From Being Called (iOS)

I added a plist database to store information for annotations in a MKMapView. Once I implemented the code to grab the information, my delegate methods are no longer being called.
The code I added was:
- (void)viewDidLoad
{
NSMutableArray *annotations = [[NSMutableArray alloc]init];
NSString *path = [[NSBundle mainBundle] pathForResource:#"MillersStores" ofType:#"plist"];
NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:path];
NSArray *anns = [dict objectForKey:#"Root"];
for(int i = 0; i < [anns count]; i++) {
float realLatitude = [[[anns objectAtIndex:i] objectForKey:#"Latitude"] floatValue];
float realLongitude = [[[anns objectAtIndex:i] objectForKey:#"Longitude"] floatValue];
MillersLocations *myAnnotation = [[MillersLocations alloc] init];
CLLocationCoordinate2D theCoordinate;
theCoordinate.latitude = realLatitude;
theCoordinate.longitude = realLongitude;
myAnnotation.coordinate = theCoordinate;
myAnnotation.title = [[anns objectAtIndex:i] objectForKey:#"Title"];
myAnnotation.subtitle = [[anns objectAtIndex:i] objectForKey:#"Address"];
[mapView addAnnotation:myAnnotation];
[annotations addObject:myAnnotation];
[myAnnotation release];
}
}
And this is one of delegate method that's no longer being called is:
- (MKAnnotationView *) mapView:(MKMapView *) mapView viewForAnnotation:(id ) annotation {
if ([annotation isKindOfClass:[MKUserLocation class]])
return nil;
MKPinAnnotationView *pinView = [[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:nil] autorelease];
pinView.pinColor = MKPinAnnotationColorRed;
pinView.animatesDrop = YES;
pinView.canShowCallout = YES;
UIImageView *leftIconView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"MillersAnnotation.png"]];
pinView.leftCalloutAccessoryView = leftIconView;
UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
pinView.rightCalloutAccessoryView = rightButton;
return pinView;
}
I have another delegate method in there that also zooms into the User's Location that's not being called either, as well as the calloutAccessoryControlTapped method that's no longer being called.
I know it has something to do with the new code, but I'm confused as to how to even debug this because it's not giving me errors and I can't log it because the entire methods aren't even being called. When I get rid of the new code, the old code works fine...What is it in the new code that negates the old code?
It sounds like the map view's delegate property is not set.
Did the old code contain this line:
mapView.delegate = self;
Add that to viewDidLoad or, in IB, connect the map view's delegate outlet to File's Owner.

Resources