这是我在后台播放触觉的方式,首先你需要在 WatchExtension 的功能中启用后台模块并启用:锻炼处理和音频,Airplay。您还需要启用 WatchExtension HealthKit。
#import <HealthKit/HealthKit.h> 添加HKWorkoutSessionDelegate
-(void)awakeWithContext:(id)context{
[super awakeWithContext:context];
HKHealthStore *cwHealthStore = [[HKHealthStore alloc] init];
cwConfiguration = [[HKWorkoutConfiguration alloc] init];
cwConfiguration.activityType = HKWorkoutActivityTypeOther;
NSError *error;
HKWorkoutSession *cwSession = [[HKWorkoutSession alloc] initWithConfiguration:cwConfiguration error:&error];
[cwSession setDelegate:self];
if (!error) {
[cwHealthStore startWorkoutSession:cwSession];
}
[self test];
}
#pragma mark WorkoutSession Delegates
- (void)workoutSession:(HKWorkoutSession *)workoutSession
didChangeToState:(HKWorkoutSessionState)toState
fromState:(HKWorkoutSessionState)fromState
date:(NSDate *)date{
NSLog(@"------>%ld", (long)toState);
}
- (void)workoutSession:(HKWorkoutSession *)workoutSession didFailWithError:(NSError *)error{
NSLog(@"%@", error);
}
现在您可以在后台播放触觉。
-(void)test{
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerTrick:) userInfo:nil repeats:true];
}
- (void)timerTrick:(NSTimer *)time {
[[WKInterfaceDevice currentDevice] playHaptic:WKHapticTypeStart];
}
离开控制器后不要忘记停止锻炼会话:
[cwHealthStore endWorkoutSession:cwSession];