MKAnnotationView 在 iOS 的 mapview 上不显示图像

MKAnnotationView not showing image on mapview in iOS

我正在从 Web 服务器获取一些图像 url,我需要将其显示在 mapview 上。我已经为 MKAnnotationView 添加了函数并解析了 url,但是它没有显示在地图视图中。下面是我的代码。如果我做错了什么,请告诉我。

- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation
{
    static NSString *identifier = @"CustomAnnotation";
    MKAnnotationView* annView = nil;
    if ([annotation isKindOfClass:[MapViewAnnotation class]]) {

        annView = (MKAnnotationView *) [mapView dequeueReusableAnnotationViewWithIdentifier:identifier];
        if (annView == nil) {
            annView = [[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:identifier];
        } else {
            annView.annotation = annotation;
        }

        for(int i=0;i<array.count;i++) {

            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

                NSURL *iconurl = [NSURL URLWithString:[[array objectAtIndex:i]valueForKey:@"icon"]];
                UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:iconurl]];

                dispatch_async(dispatch_get_main_queue(), ^ {

                    UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
                    [annView addSubview:imageView];
                    [annView setFrame:CGRectMake(0, 0, imageView.frame.size.width, imageView.frame.size.height)];
                });
            });
        }

        UIButton*accessory = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
        [accessory addTarget:self action:@selector(openDetail:) forControlEvents:UIControlEventTouchUpInside];
        [accessory setFrame:CGRectMake(0, 0, 30, 30)];
        [annView setRightCalloutAccessoryView:accessory];
    }
    [annView setEnabled:YES];
    [annView setCanShowCallout:YES];
    return annView;
}

首先,确保您已经指定了地图视图的委托,并确认您的 viewForAnnotation 被调用了。

其次,您要添加 UIImageView 作为 MKAnnotationView 的子视图。通常,您只需设置 MKAnnotationView 本身的 image 属性。