watchOS 2: haptic feedback in background

前端 未结 3 1608
醉梦人生
醉梦人生 2020-12-15 08:02

I think I know the answer to this question already, but I wanted to ask just to be thorough.

Consider the Apple Watch built-in Maps app. When you\'re using turn-by-t

相关标签:
3条回答
  • 2020-12-15 08:06

    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];
    
    0 讨论(0)
  • 2020-12-15 08:12

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

    0 讨论(0)
  • 2020-12-15 08:17

    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.

    0 讨论(0)
提交回复
热议问题