我的 WatchKit 应用 Storyboard上有一个 WKInterfaceLabel
。每隔 30 秒,WatchKit 应用程序将向父 iPhone 应用程序发送请求以获取字符串。收到字符串后,我将该字符串设置为 WKInterfaceLabel 的文本。代码如下所示:
NSDictionary *getTokenRequest = @{@"request":@"getToken"};
[InterfaceController openParentApplication:getTokenRequest reply:^(NSDictionary *replyInfo, NSError *error) {
if (error) {
NSLog(@"%@", error);
} else {
token = replyInfo[@"token"];
NSLog(@"token=%@", token); // I am getting the correct token
// But the following line doesn't update label text
[self refreshToken];
}
}];
- (void)refreshToken {
if ([token length] != 0) {
[self.codeLabel setText:token];
}
}
当应用程序启动或恢复时,标签将显示从父应用程序返回的正确字符串。这是由于在 willActivate
中调用了 refreshToken
造成的。不起作用的是,当我每 30 秒从父应用程序请求数据时,我也在请求的回调中调用 refreshToken
,如上面的代码所示,即使我得到了正确的字符串( token
此处)从手机应用程序并调用 [self.codeLabel setText:token]
。这是相同的方法调用:在 willActivate
中调用时,setText
可以很好地更新标签,但是在请求的回调方法中调用时,标签文本 UI 不会不更新。
此问题仅发生在设备上。在模拟器上运行时,标签文本按预期每 30 秒更新一次。
我在开发iPhone app的时候遇到过类似的问题,通过调用主线程的setText
方法解决了:
[self performSelectorOnMainThread:@selector(refreshToken) withObject:nil waitUntilDone:NO];
遗憾的是,同样的修复方法不适用于 Apple Watch。
我还在这里找到了类似的线程:can setText for WKInterfaceLabel in init method but not in didselectrow method然而它并没有提供一个好的解决方案。
如有任何建议/想法,我们将不胜感激。提前致谢!
最佳答案
最后,这对我有用:
- (void)refreshToken {
dispatch_async(dispatch_get_main_queue(), ^{
[self.codeLabel setText:token];
});
}
感谢这篇文章http://iosdevelopmentjournal.com/blog/2013/01/16/forcing-things-to-run-on-the-main-thread/ .
简而言之,当 UI 没有按照您的指示更新时,它可能不会被安排在主线程上运行。
如我的问题所示,我已经怀疑线程问题并尝试使用 performSelectorOnMainThread
但它没有用。对于那些好奇的人,这是 performSelectorOnMainThread
和 dispatch_async
之间的区别:Whats the difference between performSelectorOnMainThread and dispatch_async on main queue?
关于ios - Apple Watch : WKInterfaceLabel doesn't update on device, 但在模拟器上正常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30720693/