2017-06-14 31 views
0

私はリンゴの時計から、ユーザの心拍数の測定値を追跡する必要があるアプリケーションを持っているので、私は、私はリンゴのガイドで見つかったすべての必要な手順を行なったし、ここで私が使用していたコードです:HKObserverQuery

static var query: HKObserverQuery? 

    func startObservingHeartRate() { 

     guard let heartRateSampleType = HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.heartRate) else { 

      fatalError("Unable to create a step count sample type") 

     } 



     AppDelegate.query = HKObserverQuery(sampleType: heartRateSampleType, predicate: nil, updateHandler: { (query, completionHandler, error) in 

       if error != nil { 

        // Perform Proper Error Handling Here... 
        print("An error occured while setting up the Heart Rate observer.") 

       } 

       //Read the last strored heatt rate in add it to the DB 
       //Add last fetched Heart Rate reading to DB and send it to clips 
       HealthKitManager().fetchLastStoredHeartRate(completion: { (lastReading, error) in 

        guard let lastReading = lastReading else { 

         //There is no heart readings in HealthKit 
         return 

        } 

        //Check if Last HR value is Abnormal 
        if lastReading.doubleValue > 60 { 

         //TODO: - Schedule notification 
         if UIApplication.shared.applicationState == .background { 



         } else { 

         //TODO: - Show popup to the user 

         } 

        } 

       }) 

       completionHandler() 

     }) 

     healthKitStore.execute(AppDelegate.query!) 

     configureHeartRateObserver() 

    } 

    func configureHeartRateObserver() { 

     guard let heartRateSampleType = HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.heartRate) else { 

      fatalError("Unable to create a step count sample type") 

     } 

     healthKitStore.enableBackgroundDelivery(for: heartRateSampleType, frequency: HKUpdateFrequency.immediate) { (success, error) in 

      if success { 

       print("Enabled background delivery of Heart Rate changes") 

      } else { 

       print("Failed to enable background delivery of weight changes. ") 

      } 

     } 

    } 

AppDelegateのdidFinishLaunchingWithOptionsで "startObservingHeartRate"を呼び出しています。このクエリは、新しい読み取り値が追加または削除された後に実行する必要があると仮定しています。アプリがバックグラウンドであるか、私のアプリを起動し、更新を行います。

しかし、アプリをバックグラウンドに置くたびに、フォアグラウンドに戻すと、HealthKitストアに新しい読み取り値が追加されていなくても、オブザーバークエリが何度も実行されます。この場合、最後の同じ心拍数が得られます理由なく何度も

このタイプのクエリの使用方法や、現在の実装で必要な変更をお勧めします。

答えて

1

追加または削除された心拍数のサンプルをより正確にトラッキングする場合は、HKAnchoredObjectQueryを使用する必要があります。 HKObserverQueryは、サンプルが追加または削除されたときにのみ更新ハンドラが呼び出されることを保証しません。 enableBackgroundDelivery(for:frequency:completion:)も使用しているので、HKAnchoredObjectQueryに加えてHKObserverQueryを実行し続ける必要があります。