Way to update wkinterfacecontroller at runtime in watch os 2

In the title

#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

      

So I have implemented WCSessionDelegate and every time I get UI information I would like to update it. So my .m file has:

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

      

However, it is not updated. Is there a correct way to update?

+3


source to share


1 answer


You're halfway there. You have configured to receive the message correctly on the clockwork side, but you need to trigger a message to be sent when the UI is updated (so triggering didReceiveMessage

to start and update the relevant content).

If you are making changes to the user interface, you need to enable this:

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

      



Also, make sure you activate correctly WCSession

. This is usually done in viewDidLoad

or willAppear

depending on whether you are implementing it on a phone or a watch.

- (void)viewDidLoad {
    [super viewDidLoad];

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

      

In this tutorial, you can see a complete example of end-to-end data transfer from iPhone to iPhone - http://www.kristinathai.com/watchos-2-tutorial-using-sendmessage-for-instantaneous-data-transfer-watch-connectivity-1

+11


source







All Articles