Objective-C: Pass a map snapshot to view controller in prepareForSegue

100 views Asked by At

I'm trying to segue from a mapView to a page that contains a snapshot of a chosen location on that mapView.

Here is my prepareForSegue method:

- (void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([segue.identifier isEqualToString:@"LocationConfirmSegue"]) {
        LocationConfirmationViewController *vc = segue.destinationViewController;

        MKCoordinateSpan span;
        span.longitudeDelta = mapFocusSpan;
        span.latitudeDelta = mapFocusSpan;

        MKCoordinateRegion region;
        region.center = *currentPinLocation;
        region.span = span;

        MKMapSnapshotOptions *options = [[MKMapSnapshotOptions alloc] init];
        options.region = region;
        options.size = CGSizeMake(270, 180);

        MKMapSnapshotter *snapshotter = [[MKMapSnapshotter alloc] initWithOptions:options];
        [snapshotter startWithCompletionHandler:    ^(MKMapSnapshot * _Nullable snapshot, NSError * _Nullable error) {
            if (error) {
                NSLog(@"%@", error);
                return;
            }

            vc.mapSnapshot = snapshot.image;
        }];
    }
}

I can pass information to the destination VC fine outside of the snapshotter's completion handler. The code all works fine, too––snapshot.image does indeed return a UIImage*––however it's not being passed to the destination view controller. When I try to access the mapSnapshot property in that view controller, I get (null).

1

There are 1 answers

0
Tim On

Take advantage of Apple's OpenGLES screenshot to prevent the inability to get a layer image of the map or a black screen

-(UIImage *)zjcCutScreenImage {
NSInteger myDataLength = self.width * self.height * 4; 
GLubyte *buffer = (GLubyte *) malloc(myDataLength);
glReadPixels(0, 0, self.width, self.height, GL_RGBA, GL_UNSIGNED_BYTE, buffer);
GLubyte *buffer2 = (GLubyte *) malloc(myDataLength);
for(int y = 0; y <self.height; y++) {
    for(int x = 0; x <self.width * 4; x++){
        buffer2[(JSNDHC - y) * self.width * 4 + x] = buffer[y * 4 * 1024 + x];
    }
}
CGDataProviderRef provider = CGDataProviderCreateWithData(NULL, buffer2, myDataLength, NULL);
int bitsPerComponent = 8;
int bitsPerPixel = 32;
int bytesPerRow = 4 * self.height;
CGColorSpaceRef colorSpaceRef = CGColorSpaceCreateDeviceRGB();
CGBitmapInfo bitmapInfo = kCGBitmapByteOrderDefault;
CGColorRenderingIntent renderingIntent = kCGRenderingIntentDefault;
CGImageRef imageRef = CGImageCreate(self.width, self.height, bitsPerComponent, bitsPerPixel, bytesPerRow, colorSpaceRef, bitmapInfo, provider, NULL, NO, renderingIntent);
UIImage *myImage = [UIImage imageWithCGImage:imageRef];
return myImage;
}