2017-11-07 14 views
0

今、ユーザーがステップカウントを更新したときに関数が呼び出されるようにアプリケーションを設定しようとしています。これまでのところ、私は次のコードを持っている:ステップカウントが更新されたときに何かを呼び出す

let steps: HKObjectType = HKObjectType.quantityType(forIdentifier: .stepCount)! 
    if healthStore.authorizationStatus(for: steps) != HKAuthorizationStatus.notDetermined { 
     healthStore.enableBackgroundDelivery(for: steps, frequency: .immediate, withCompletion: { (worked, error) in 
      //registers for background data 
      if error != nil { 
       print(error) 
      } 
     }) 
     let sampleType = HKSampleType.quantityType(forIdentifier: HKQuantityTypeIdentifier.stepCount)! 
     let query = HKObserverQuery(sampleType: sampleType, predicate: nil) { 
      query, completionHandler, error in 

      if error != nil { 
       print(error) 
       abort() 
      } 

      // Take whatever steps are necessary to update your app's data and UI 
      // This may involve executing other queries 
      self.getSteps(completion: { (stepCount) in 
       print("Step count was updated to \(stepCount)") 
      }) 
      completionHandler() 
     } 

     healthStore.execute(query) 
    } 

しかし、ユーザーのstepCountがバックグラウンドで更新されたときにgetSteps方法は時にフォアグラウンドで作業をしていますが、これは、呼び出されません。私はこれについて正しく行きますか、それとも私はできないことをしようとしていますか?

+0

デバイスがロックされていない限り、バックグラウンドでの配信が可能かもしれません...この回答をチェックしてください詳細については、特にVictor Siglerの回答https://stackoverflow.com/questions/26375767/healthkit-background-delivery-when-app-is-not-running? –

答えて

1

コードが正しいように見えます。実際のデバイスではなくシミュレータで実行していますか?私は最近この問題を抱えており、バックグラウンドの配信はシミュレータではまったく動作しませんが、実際のデバイスで動作します

+0

それは問題だった、ありがとう。 – LFHS

関連する問題