了解handleWatchKitExtensionRequest

我正在testingiPhone应用程序的一些代码的执行。 我遵循苹果build议的文档(不使用后台任务,只是一个控制台日志 )。 但是,我没有得到任何东西(我想看到string“你好”)。

这是因为我在模拟器上运行WatchKit扩展应用程序 ? 还是有什么我失踪?


苹果说:

如果您使用的是openParentApplication:reply:,请确保您在input应用程序后立即创build后台任务:handleWatchKitExtensionRequest:reply :. 这将确保iPhone应用程序在后台获取时间,而不是再次被挂起。 此外,将调用包装为endBackgroundTask:在dispatch_after中保持2秒,以确保iPhone应用程序有时间再次发送答复,然后再次被暂停。

我在WatchKit扩展(链接到button的操作方法)上的实现:

- (IBAction)sendMessageToApp{ NSString *requestString = [NSString stringWithFormat:@"executeMethodA"]; // This string is arbitrary, just must match here and at the iPhone side of the implementation. NSDictionary *applicationData = [[NSDictionary alloc] initWithObjects:@[requestString] forKeys:@[@"theRequestString"]]; [WKInterfaceController openParentApplication:applicationData reply:^(NSDictionary *replyInfo, NSError *error) { NSLog(@"\nReply info: %@\nError: %@",replyInfo, error); }]; NSLog(@"sending message.."); } 

我在AppDelegate.m文件上的实现:

 - (void)application:(UIApplication *)application handleWatchKitExtensionRequest:(NSDictionary *)userInfo reply:(void(^)(NSDictionary *replyInfo))reply { NSString * request = [userInfo objectForKey:@"requestString"]; NSLog(@"howdy"); // This is just an example of what you could return. The one requirement is // you do have to execute the reply block, even if it is just to 'reply(nil)'. // All of the objects in the dictionary [must be serializable to a property list file][3]. // If necessary, you can covert other objects to NSData blobs first. NSArray * objects = [[NSArray alloc] initWithObjects:[NSDate date],[NSDate date],[NSDate date], [NSDate date], nil]; NSArray * keys = [[NSArray alloc] initWithObjects:@"objectAName", @"objectdName", @"objectBName", @"objectCName", nil]; NSDictionary * replyContent = [[NSDictionary alloc] initWithObjects:objects forKeys:keys]; reply(replyContent); } 

我在控制台中得到什么:

 2015-04-16 14:43:44.034 FanLink WatchKit Extension[3324:142904] <InterfaceController: 0x608000081fe0> initWithContext 2015-04-16 14:44:04.848 FanLink WatchKit Extension[3324:142904] sennding message.. 2015-04-16 14:44:04.854 FanLink WatchKit Extension[3324:142904] Reply info: { objectAName = "2015-04-16 13:44:04 +0000"; objectBName = "2015-04-16 13:44:04 +0000"; objectCName = "2015-04-16 13:44:04 +0000"; objectdName = "2015-04-16 13:44:04 +0000"; } Error: (null) 

这是因为您只是在debuggingWatchKit扩展目标。 如果您想在控制台中看到主应用程序日志,则需要通过Xcodedebugging器附加主应用程序的进程。 进入debugging – >附加进程 – >(然后通过标识符select并键入您的应用程序名称)

为了更好的解决问题,我特别为WatchKit / WatchKit扩展debuggingfind了这个很好的资源: https ://mkswap.net/m/blog/How+to+debug+an+iOS+app+while+the+WatchKit+ 应用+中+目前在+ + +的模拟器中运行+

  • 你的控制台日志是正确的,因为你目前debuggingWatchKit扩展目标所以你将会收到用WatchKit扩展写的日志。 用iOS App编写的NSLog不会打印在控制台中。

不知道是否偏离主题,但在上面的代码包中有一个简单的错误,有initWithObjects:@ [requestString] forKeys:@ [@“theRequestString”]

并在appdelegate NSString * request = [userInfo objectForKey:@“requestString”];

“theRequestString”不核心指向“requestString”

花了我一些时间来弄清楚为什么我的function不启动

感谢它帮助的代码