我正在尝试从我的AppDelegate调用plotParkingLots
,因为我希望在应用程序启动时首先调用它(然后每隔x秒我将在稍后实现)。
plotParkingLots
调用它, viewDidLoad
工作正常,但是当我从AppDelegate调用它时,它不起作用。
我知道它被调用但是当我切换到我的地图视图时,没有显示注释!
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;
}
答案 0 :(得分:1)
您不是在与向用户显示的MapViewController交谈。在你的AppDelegate中你暂时分配一个MapViewController,绘制停车场,然后放弃那个MapViewController,再也不用了。
您需要保留该控制器的句柄,以便当用户按下某些内容以使该控件显示时,它与刚刚绘制的停车场相同。