handleWatchKitExtensionRequest +异步调用

时间:2015-06-15 07:06:46

标签: ios watchkit

我正在尝试使用MKMapSnapshotter从包含iPhone应用程序上的地图拍摄快照,然后将图像发送回手表。当包含的iPhone应用程序没有在后台运行时,我无法让它工作。

这就是我要做的事情:

在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];
});
}

我正在尝试人们提出的不同代码,但我应该在这里做错事。请注意,“snapshotter startWithCompletionHandler”是异步完成的。

我已经尝试了以下建议,但我应该在这里遗漏一些东西。 https://stackoverflow.com/a/30000323/4982919

非常感谢任何评论和帮助。

0 个答案:

没有答案