0
我試圖從我的AppDelegate中調用plotParkingLots
,因爲我希望在應用程序啓動時(然後每隔x秒我將稍後執行)首先調用它。添加註釋以從另一個視圖映射
plotParkingLots
工作正常,如果我通過我的MapViewController的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;
}
我明白你的意思,但不知道該怎麼做。我可以使用Singleton MapViewController嗎?這是一個很好的解決方案嗎? –
你在哪裏創建MapViewController以將其顯示給用戶?如果直到用戶單擊某個按鈕纔會顯示,那麼爲什麼要將其加載數據?他們甚至可能不會去那個屏幕。如果他們確實去了那個屏幕,你必須創建一個MapViewController然後顯示它。您可以在應用程序啓動完成後獲取數據,然後在您初始化時才傳遞數據。 – Craig