Loading annotations from url using background thread. Pins doesn't show before moving or scaling mapView

夙愿已清 提交于 2019-12-02 03:48:07

问题


I load annotations from url using background thread. Pins doesn't show before I move or scale mapView. How can I update my view?

My viewDidAppear

- (void)viewDidAppear:(BOOL)animated
{

[super viewDidAppear:animated];

//Create the thread 
[NSThread detachNewThreadSelector:@selector(loadPList) toTarget:self withObject:nil];

}

loadPList

- (void) loadPList { //Load the plist NSString *urlStr = [[NSString alloc] initWithFormat:@"http://www.domain.com/data.xml"];

NSURL *url = [NSURL URLWithString:urlStr]; NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfURL:url];

NSMutableArray *annotations = [[NSMutableArray alloc]init];

NSArray *annotationsOnMap = mapView.annotations; if ([annotationsOnMap count] > [annotations count]) { [mapView removeAnnotations:annotationsOnMap];

} else { //Do nothing }

if ([[NSUserDefaults standardUserDefaults] boolForKey:@"blackKey"]) {

NSArray *ann = [dict objectForKey:@"Category1"];

for(int i = 0; i < [ann count]; i++) {

    NSString *coordinates = [[ann objectAtIndex:i] objectForKey:@"Coordinates"];

    double realLatitude = [[[coordinates componentsSeparatedByString:@","] objectAtIndex:1] doubleValue];
    double realLongitude = [[[coordinates componentsSeparatedByString:@","] objectAtIndex:0] doubleValue];

    MyAnnotation *myAnnotation = [[MyAnnotation alloc] init];
    CLLocationCoordinate2D theCoordinate;
    theCoordinate.latitude = realLatitude;
    theCoordinate.longitude = realLongitude;

    myAnnotation.coordinate=CLLocationCoordinate2DMake(realLatitude,realLongitude);

    myAnnotation.title = [[ann objectAtIndex:i] objectForKey:@"Name"];
    myAnnotation.subtitle = [[ann objectAtIndex:i] objectForKey:@"Address"];
    myAnnotation.icon = [[ann objectAtIndex:0] objectForKey:@"Icon"];


    [mapView addAnnotation:myAnnotation];
    [annotations addObject:myAnnotation];



}
}

else { //Do nothing }

//And same with other categories....

//Update the ui dispatch_async(dispatch_get_main_queue(), ^{

}); }

回答1:


You are updating the UI from a non UI - Thread this will not work

You will have to call segments of code that update your ui inside the UIThread Block as following:

For example

[mapView removeAnnotations:annotationsOnMap];

must be called in UI-Thread

   dispatch_async(dispatch_get_main_queue(), ^{
        //Update UI if you have to
        [mapView removeAnnotations:annotationsOnMap];
    });

Please note that you have to call all your UI updates inside the main_queue thread

   dispatch_async(dispatch_get_main_queue(), ^{
        //All UI updating code must come here
    });


来源:https://stackoverflow.com/questions/10862914/loading-annotations-from-url-using-background-thread-pins-doesnt-show-before-m

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!