在watch os 2中运行时更新wkinterfacecontroller的方法

Jie*_* Hu 3 objective-c watchkit watchos-2

在头文件中

#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
Run Code Online (Sandbox Code Playgroud)

所以我实现了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"]];
    }
}
Run Code Online (Sandbox Code Playgroud)

- (void)handleUIUpdateInfo:(NSDictionary*)updateInfo{
    [self.songTitleLabel setText:[updateInfo objectForKey:@"nowPlayingSongTitle"]];
    [self.playSongButton setBackgroundImage:[updateInfo objectForKey:@"playButtonImage"]];
}
Run Code Online (Sandbox Code Playgroud)

但是,它似乎没有更新.有没有适当的更新方式?

小智 11

你在那里一半.您已配置正确地在手表端接收消息,但是您需要在更新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
                           }
 ];
Run Code Online (Sandbox Code Playgroud)

此外,请确保您WCSession正确激活.这通常是在您手机或手表上实现viewDidLoadwillAppear取决于您是在手机还是手表上实现.

- (void)viewDidLoad {
    [super viewDidLoad];

    if ([WCSession isSupported]) {
        WCSession *session = [WCSession defaultSession];
        session.delegate = self;
        [session activateSession];
    }
}
Run Code Online (Sandbox Code Playgroud)

您可以在本教程中看到端到端Watch to iPhone数据传输的完整示例 - http://www.kristinathai.com/watchos-2-tutorial-using-sendmessage-for-instantaneous-data-transfer-看-连接- 1