私のアプリでは、時計の InterfaceController から電話の HomeViewController に情報を送信する必要があります。しかし、コードを実行すると、情報は一度しか機能しません。再び機能させるには、Apple Watch アプリを削除して再インストールする必要があります。
InterfaceController.m:
#import "InterfaceController.h"
#import <WatchConnectivity/WatchConnectivity.h>
@interface InterfaceController() <WCSessionDelegate>
@property (strong, nonatomic) WCSession *session;
@end
@implementation InterfaceController
-(instancetype)init {
self = [super init];
if (self) {
if ([WCSession isSupported]) {
self.session = [WCSession defaultSession];
self.session.delegate = self;
[self.session activateSession];
}
}
return self;
}
-(void)sendText:(NSString *)text {
NSDictionary *applicationDict = @{@"text":text};
[self.session updateApplicationContext:applicationDict error:nil];
}
- (IBAction)ButtonPressed {
[self sendText:@"Hello World"];
}
HomeViewController.m:
#import "HomeViewController.h"
#import <WatchConnectivity/WatchConnectivity.h>
@interface HomeViewController ()<WCSessionDelegate>
@end
@implementation HomeViewController
@synthesize TextLabel;
- (void)viewDidLoad {
[super viewDidLoad];
if ([WCSession isSupported]) {
WCSession *session = [WCSession defaultSession];
session.delegate = self;
[session activateSession];
}
}
- (void)session:(nonnull WCSession *)session didReceiveApplicationContext:(nonnull NSDictionary<NSString *,id> *)applicationContext {
NSString *text = [applicationContext objectForKey:@"text"];
dispatch_async(dispatch_get_main_queue(), ^{
[TextLabel setText:text];
});
}
前述のように、iOS ラベルは「Hello World」に一度だけ変更されます。iOS アプリを再起動した後、そのテキスト ラベルに「Hello World」と表示されなくなった後、時計で iOS テキスト ラベルを「Hello World」に戻すことができません。
これは、時計と iPhone 間の通信の問題ですか、それともコードの問題ですか?