I am trying to use MKMapSnapshotter to take a snapshot from the Map on the containing iPhone app, and then send the image back to the watch. When the containing iPhone app is not running on the background, I cannot get it to work.
This is how I am trying to do:
on AppDelegate:
- (void)application:(UIApplication *)application handleWatchKitExtensionRequest:(NSDictionary *)userInfo reply:(void ( ^)( NSDictionary * ))reply {
__block UIBackgroundTaskIdentifier watchKitHandler;
watchKitHandler = [[UIApplication sharedApplication]
beginBackgroundTaskWithName:@"backgroundTask" expirationHandler:^{
watchKitHandler = UIBackgroundTaskInvalid;
}];
NSMutableDictionary *response = [NSMutableDictionary dictionary];
dispatch_semaphore_t sema = dispatch_semaphore_create(0);
//========================Building the snapshot===========
CLLocationDegrees latitude = 37.331793f;
CLLocationDegrees longitude = -122.029584f;
MKMapView* mapView = [[MKMapView alloc] initWithFrame:CGRectMake(0, 0, (156*2), (108*2))];
mapView.mapType = MKMapTypeHybrid;
CLLocationCoordinate2D coord = CLLocationCoordinate2DMake(latitude, longitude);
MKCoordinateSpan span = {.latitudeDelta = 0.01, .longitudeDelta = 0.01};
MKCoordinateRegion region = {coord, span};
[mapView setRegion:region];
MKMapSnapshotOptions *options = [[MKMapSnapshotOptions alloc] init];
options.region = mapView.region;
options.size = mapView.frame.size;
options.scale = [[UIScreen mainScreen] scale];
MKMapSnapshotter *snapshotter = [[MKMapSnapshotter alloc] initWithOptions:options];
//========================================================
[snapshotter startWithCompletionHandler:^(MKMapSnapshot *snapshot, NSError *error) {
NSData *imageData = UIImagePNGRepresentation(snapshot.image);
[response setObject:imageData forKey:@"snapshotimage"];
reply(response);
}];
dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
dispatch_after(dispatch_time( DISPATCH_TIME_NOW, (int64_t)NSEC_PER_SEC * 1), dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[[UIApplication sharedApplication] endBackgroundTask:watchKitHandler];
});
}
I am trying different codes suggested by people but I should be doing something wrong in here. Please notice that the "snapshotter startWithCompletionHandler" is done asynchronously.
I have tried the following suggestions but I should be missing something here. https://stackoverflow.com/a/30000323/4982919
Any comment and help is greatly appreciated.