我正在尝试使用 WCSession 将数据从我的 iOS 应用程序发送到配套的 WatchOS 应用程序。iOS 应用程序是使用 NativeScript 创建的,因此需要 Objective-C。
在模拟器和真实设备上运行应用程序时,我收到以下错误消息:
[WC] WCSession 缺少它的代表
我已经搞砸了几天,但无法解决这个问题。
iOS Objective-C 代码(在 Typescript 中调用):
#import "SendToWatch.h"
#import <WatchConnectivity/WatchConnectivity.h>
@interface SendToWatch () <WCSessionDelegate>
@end
@implementation SendToWatch
- (void)sendData: (double)value {
if (WCSession.isSupported) {
WCSession *session = [WCSession defaultSession];
session.delegate = self;
[session activateSession];
NSError *error = nil;
NSDictionary *applicationDict = @{@"data":[NSString stringWithFormat:@"%0.2f", value]};
[session updateApplicationContext:applicationDict error:nil];
if (error) {
NSLog(@"%@", error.localizedDescription);
}
}
}
//MARK: - WCSessionDelegate
- (void)session:(WCSession *)session
activationDidCompleteWithState:(WCSessionActivationState)activationState
error:(NSError *)error {
}
- (void)sessionDidBecomeInactive:(WCSession *)session {
NSLog(@"Session Did Become Inactive");
}
- (void)sessionDidDeactivate:(WCSession *)session {
NSLog(@"-- Session Did Deactivate --");
[session activateSession];
}
@end
WatchOS(接口控制器.m):
#import "InterfaceController.h"
#import <WatchConnectivity/WatchConnectivity.h>
@interface InterfaceController () <WCSessionDelegate>
@end
@implementation InterfaceController
- (void)awakeWithContext:(id)context {
[super awakeWithContext:context];
// Creates a WCSession to allow iPhone connectivity
if ([WCSession isSupported]) {
WCSession *session = [WCSession defaultSession];
session.delegate = self;
[session activateSession];
NSLog(@"-- WCSession Active --");
}
}
- (void)willActivate {
[super willActivate];
NSLog(@"-- Controller Activated --");
}
- (void)didDeactivate {
[super didDeactivate];
NSLog(@"-- Controller Deactive --");
}
//MARK: - WCSessionDelegate
// Receieves the data sent from the iPhone app
- (void)session:(nonnull WCSession *)session didReceiveApplicationContext:(nonnull NSDictionary *)applicationContext {
NSString *receivedData = [applicationContext objectForKey:@"data"];
NSLog(@"-- APPLICATION CONTEXT RECEIVED --");
NSLog(@"-- Received from iOS App: %@", applicationContext);
dispatch_async(dispatch_get_main_queue(), ^{
[self.dataLabel setText:receivedData];
NSLog(@"-- DATA UPDATED --");
});
}
- (void)session:(WCSession *)session activationDidCompleteWithState:(WCSessionActivationState)activationState error:(NSError *)error {
}
@end