I'm trying to take a screenshot of my MKMapView. I usually achieved this using the below code in Objective C.
I'm wondering how I would keep the NSData object in memory, rather than saving the image, and then reading from it straight away.
I'm also wondering how this could be written in Swift - In particular, the completion handler part. I've looked at the docs - but unsure of syntax:https://developer.apple.com/library/prerelease/iOS/documentation/MapKit/Reference/MKMapSnapshotter_class/index.html#//apple_ref/c/tdef/MKMapSnapshotCompletionHandler
MKMapSnapshotOptions *options = [[MKMapSnapshotOptions alloc] init];
options.region = self.mapView.region;
options.size = self.mapView.frame.size;
options.scale = [[UIScreen mainScreen] scale];
NSURL *fileURL = [NSURL fileURLWithPath:@"path/to/snapshot.png"];
MKMapSnapshotter *snapshotter = [[MKMapSnapshotter alloc] initWithOptions:options];
[snapshotter startWithCompletionHandler:^(MKMapSnapshot *snapshot, NSError *error) {
if (error) {
NSLog(@"[Error] %@", error);
return;
}
UIImage *image = snapshot.image;
NSData *data = UIImagePNGRepresentation(image);
[data writeToURL:fileURL atomically:YES];
}];
In terms of "keeping" it in memory, you could return the
NSData
via an Objective-C completion block (or Swift closure). From there, you can pass theNSData
to another method or save it in a class property.For example, in Objective-C:
The Swift equivalent is:
Frankly, if you're trying to use the
UIImage
somewhere else, I might change these block/closure parameters to use theUIImage
rather than theNSData
, but hopefully this illustrates the idea.