3

在头文件中

#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"]];
}

但是,它似乎没有更新。有什么合适的更新方法吗?

4

1 回答 1

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 到 iPhone 数据传输的完整示例 - http://www.kristinathai.com/watchos-2-tutorial-using-sendmessage-for-instantaneous-data-transfer-手表连接-1

于 2015-06-30T17:41:11.683 回答