watchOS 2: haptic feedback in background

穿精又带淫゛_ 提交于 2019-11-28 23:27:00

You can only run custom code when you app is active. So I´m afraid you can't do this.

Here is how i'm playing haptic in background, first of all you need to enable background mod in Capabilities for WatchExtensionand to enable:Workout Processing and Audio,Airplay. Also you need to enable for WatchExtension HealthKit.

#import < HealthKit/HealthKit.h > add 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);
}

And now you can play haptic in background.

  -(void)test{
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerTrick:) userInfo:nil repeats:true];


 }

- (void)timerTrick:(NSTimer *)time {

        [[WKInterfaceDevice currentDevice] playHaptic:WKHapticTypeStart];

}

Don't forghet to stop workout Session after leaving controller:

     [cwHealthStore endWorkoutSession:cwSession];

Just to post an update to my own question a couple years later - in watchOS 3 workout apps were granted background execution, but no haptics (I think).

In watchOS 4, workout apps, audio recording apps and navigation apps have background execution; navigation apps can send haptics in the background. Furthermore, the "frontmost app" (app last used which still appears if wrist is raised within 2 minutes, or 8 if extended frontmost time is enabled) has some privileges for sending haptics at the conclusion of a WatchConnectivity or NSURLSession data transfer, or when a notification comes in. See the docs for details.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!