objective-c - 在 watch os 2 运行时更新 wkinterfacecontroller 的方法

标签 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

所以我实现了 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。这通常在 viewDidLoadwillAppear 中完成,具体取决于您是在手机上还是在 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/

相关文章:

ios - WatchKit 不下载图片

ios - 在 Watch OS 2 中加载 Glance 不一致

ios - Apple Watch 和 iOS 与物联网设备的通信

ios - 如何将.rtf文件显示到UITextView中

objective-c - 什么时候在 Objective-C++ 中销毁 C++ 对象?

ios - 将 NSMutableArray 转换为具有相同顺序的 NSSet

ios - Watchkit:如何在 Objective c 中从左到右循环图像?

ios - sessionReachabilityDidChange 未在 watch 上调用

ios - 在 watchOS2 中使用 WatchConnectivity 在 iOS 和 WatchOS 之间发送消息

objective-c - NSPredicate 编辑器以编程方式更改控件高度