あなたが探している方法はこれだと思います:
-(void)application:(UIApplication *)application handleWatchKitExtensionRequest:(NSDictionary *)userInfo reply:(void (^)(NSDictionary *))reply
iPhone アプリの AppDelegate.m ファイルに、このメソッドを追加する必要があります。メソッド内で使用する必要があります
__block UIBackgroundTaskIdentifier watchKitHandler;
watchKitHandler = [[UIApplication sharedApplication] beginBackgroundTaskWithName:@"backgroundTask"
expirationHandler:^{
watchKitHandler = UIBackgroundTaskInvalid;
}];
と
dispatch_after( dispatch_time( DISPATCH_TIME_NOW, (int64_t)NSEC_PER_SEC * 10), dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0 ), ^{
[[UIApplication sharedApplication] endBackgroundTask:watchKitHandler];
} );
全体として、iPhone アプリのメソッドは次のようになります。
//handle watch app request
-(void)application:(UIApplication *)application handleWatchKitExtensionRequest:(NSDictionary *)userInfo reply:(void (^)(NSDictionary *))reply
{
//Make it a background task
__block UIBackgroundTaskIdentifier watchKitHandler;
watchKitHandler = [[UIApplication sharedApplication] beginBackgroundTaskWithName:@"backgroundTask"
expirationHandler:^{
watchKitHandler = UIBackgroundTaskInvalid;
}];
NSString* command = [userInfo objectForKey:@"command"];
if ([command isEqualToString:@"request"]) {
//do some action here
// use the reply dictionary if necessary
NSDictionary *responseObject = @{@"info": @"some Info"};
reply(responseObject);
} else if ([command isEqualToString:@"request2"]) {
// do some other action here
}
//finish background task
dispatch_after( dispatch_time( DISPATCH_TIME_NOW, (int64_t)NSEC_PER_SEC * 10), dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0 ), ^{
[[UIApplication sharedApplication] endBackgroundTask:watchKitHandler];
} );
}
時計側では、次のコードを使用する必要があります。
NSDictionary *request = @{ @"command": @"request", @"info": @"some additional things here for example"};
[WKInterfaceController openParentApplication:request reply:^(NSDictionary *replyInfo, NSError *error ) {
//do something with the reply dictionary here
NSLog(@"%@", replyInfo);
}];
お役に立てば幸いです。
編集:
このコードは、watchOS 1 でのみ機能します。既に watchOS 2 向けに開発している場合は、Watch Connectivity Frameworkを参照してください。