Search code examples
iosmkmapviewmkannotationview

MKAnnotationView not showing image on mapview in iOS


I am getting some image url from web server, which I need to display on mapview. I have added function for MKAnnotationView and parsed the url, however its not showing on map view. Below is my code. Please let me know, if I am doing anything wrong.

- (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;
}

Solution

  • First, make sure you've specified the delegate of the map view and confirm that your viewForAnnotation is getting called at all.

    Second, you're adding the UIImageView as a subview of the MKAnnotationView. Generally you just set the image property of the MKAnnotationView itself.