要从iPhone向Apple Watch发送数据,你可以使用WatchConnectivity框架。这个框架允许你在iPhone和Apple Watch之间进行通信。以下是如何使用Objective-C从iPhone向Apple Watch发送一个整数(int)的步骤:
WatchConnectivity框架提供了两种通信方式:会话(Session)和消息传递(Message Passing)。会话用于持续的数据同步,而消息传递用于一次性数据传输。
#import <WatchConnectivity/WatchConnectivity.h>
@interface ViewController () <WCSessionDelegate>
@property (nonatomic, strong) WCSession *session;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
if ([WCSession isSupported]) {
self.session = [WCSession defaultSession];
self.session.delegate = self;
[self.session activateSession];
}
}
#pragma mark - WCSessionDelegate
- (void)session:(WCSession *)session activationDidCompleteWithState:(WCSessionActivationState)activationState error:(NSError *)error {
// Handle session activation completion
}
- (void)session:(WCSession *)session didReceiveMessage:(NSDictionary<NSString *,id> *)message {
// Handle incoming messages
}
@end
- (void)sendIntToWatch:(int)value {
if ([self.session isReachable]) {
NSDictionary *message = @{@"intValue": @(value)};
[self.session sendMessage:message replyHandler:^(NSDictionary<NSString *,id> * _Nonnull replyMessage) {
// Handle reply from watch
} errorHandler:^(NSError * _Nonnull error) {
// Handle error
}];
}
}
#import <WatchConnectivity/WatchConnectivity.h>
@interface InterfaceController () <WCSessionDelegate>
@end
@implementation InterfaceController
- (void)awakeWithContext:(id)context {
[super awakeWithContext:context];
if ([WCSession isSupported]) {
WCSession *session = [WCSession defaultSession];
session.delegate = self;
[session activateSession];
}
}
#pragma mark - WCSessionDelegate
- (void)session:(WCSession *)session didReceiveMessage:(NSDictionary<NSString *,id> *)message {
NSNumber *intValue = message[@"intValue"];
if (intValue) {
int value = [intValue intValue];
// Handle the received integer value
}
}
@end
通过以上步骤,你可以成功地从iPhone向Apple Watch发送一个整数。希望这对你有所帮助!
领取专属 10元无门槛券
手把手带您无忧上云