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

时间:2015-06-29 20:04:50

标签: objective-c watchkit watch-os-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

所以我实现了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"]];
    }
}

AND

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

然而,它似乎没有更新。有没有正确的更新方式?

1 个答案:

答案 0 :(得分: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
                           }
 ];

另外,请务必正确激活WCSession。这通常在viewDidLoadwillAppear中完成,具体取决于您是在手机还是手表上实现此功能。

- (void)viewDidLoad {
    [super viewDidLoad];

    if ([WCSession isSupported]) {
        WCSession *session = [WCSession defaultSession];
        session.delegate = self;
        [session activateSession];
    }
}

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