在头文件中
#import <WatchKit/WatchKit.h>
#import <Foundation/Foundation.h>
#import <WatchConnectivity/WatchConnectivity.h>
@interface InterfaceController : WKInterfaceController<WCSessionDelegate>
- (IBAction)lastSongButtonClick;
- (IBAction)playSongButtonClick;
- (IBAction)nextSongButtonClick;
@property (strong, nonatomic) IBOutlet WKInterfaceLabel *songTitleLabel;
@property (strong, nonatomic) IBOutlet WKInterfaceButton *playSongButton;
@end
所以我实现了 WCSessionDelegate,每次收到有关 UI 的信息时,我都希望它更新。所以在我的 .m 文件中我有:
- (void)session:(nonnull WCSession *)session didReceiveMessage:(nonnull NSDictionary<NSString *,id> *)message{
NSString* type = [message objectForKey:@"type"];
if([type isEqualToString:@"UIUpdateInfo"]){
NSLog(@"Watch receives UI update info");
[self handleUIUpdateInfo:[message objectForKey:@"content"]];
}
}
和
- (void)handleUIUpdateInfo:(NSDictionary*)updateInfo{
[self.songTitleLabel setText:[updateInfo objectForKey:@"nowPlayingSongTitle"]];
[self.playSongButton setBackgroundImage:[updateInfo objectForKey:@"playButtonImage"]];
}
然而,它似乎没有更新。有什么正确的更新方法吗?
最佳答案
你已经完成了一半。您已正确配置在 watch 端接收消息,但您需要在更新 UI 时触发发送消息(因此触发 didReceiveMessage
执行并更新适当的内容)。
无论在何处对 UI 进行更改,都需要包含以下内容:
NSDictionary *message = //dictionary of info you want to send
[[WCSession defaultSession] sendMessage:message
replyHandler:^(NSDictionary *reply) {
//handle reply didReceiveMessage here
}
errorHandler:^(NSError *error) {
//catch any errors here
}
];
此外,请确保您正确激活了 WCSession
。这通常在 viewDidLoad
或 willAppear
中完成,具体取决于您是在手机上还是在 watch 上实现。
- (void)viewDidLoad {
[super viewDidLoad];
if ([WCSession isSupported]) {
WCSession *session = [WCSession defaultSession];
session.delegate = self;
[session activateSession];
}
}
您可以在本教程中看到端到端 Watch 到 iPhone 数据传输的完整示例 - http://www.kristinathai.com/watchos-2-tutorial-using-sendmessage-for-instantaneous-data-transfer-watch-connectivity-1
关于objective-c - 在 watch os 2 运行时更新 wkinterfacecontroller 的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31124600/