我认为您正在寻找的方法是这个:
-(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。