Reputation: 1082
I'm trying to call plotParkingLots
from my AppDelegate as I want it to be called first when the app starts (and then every x seconds which I will implement later).
plotParkingLots
works fine if I call it through my MapViewController's viewDidLoad
, but when I call it from AppDelegate, it doesn't work.
I know that it is called but when I switch to my map view, no annotation is shown!
MapViewController.h
#import <UIKit/UIKit.h>
#import <MapKit/MapKit.h>
#define METERS_PER_MILE 1609.344
@interface MapViewController : UIViewController <MKMapViewDelegate>
@property (strong, nonatomic) IBOutlet MKMapView *mapView;
- (void)plotParkingLots;
@end
MapViewController.m
- (void)plotParkingLots {
NSString *url = [NSString stringWithFormat:@"http:/localhost/testes/parking.json"];
NSData *jsonData = [NSData dataWithContentsOfURL: [NSURL URLWithString:url]];
if (jsonData == nil) {
UIAlertView *alertBox = [[UIAlertView alloc] initWithTitle: @"Erro de conexão" message: @"Não foi possível retornar os dados dos estacionamentos" delegate: self cancelButtonTitle: @"Ok" otherButtonTitles: nil];
[alertBox show];
}
else {
NSError *error;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
NSArray *parkings = [json objectForKey:@"parkings"];
for (NSDictionary * p in parkings) {
Parking *annotation = [[Parking alloc] initWithDictionary:p];
[_mapView addAnnotation:annotation];
}
}
}
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation {
static NSString *identifier = @"Parking";
if ([annotation isKindOfClass:[Parking class]]) {
MKPinAnnotationView *annotationView = (MKPinAnnotationView *) [_mapView dequeueReusableAnnotationViewWithIdentifier:identifier];
if (annotationView == nil) {
annotationView = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:identifier];
} else {
annotationView.annotation = annotation;
}
annotationView.enabled = YES;
annotationView.canShowCallout = YES;
annotationView.image=[UIImage imageNamed:@"car.png"];
return annotationView;
}
return nil;
}
AppDelegate.m
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Override point for customization after application launch.
[[MapViewController alloc] plotParkingLots];
return YES;
}
Upvotes: 0
Views: 377
Reputation: 8294
You're not talking to the MapViewController that is displayed to the user. In your AppDelegate you momentarily allocation a MapViewController, plot the parking lots, then abandon that MapViewController and never use it again.
You'll need to keep a handle to that controller so that when the user presses something to make that viewcontroller get displayed it is the same one that has just plotted the parking lots.
Upvotes: 1