2016-07-21 2 views
1

私は健康管理キットから有効エネルギー(kcal)を読み取る方法に取り組んでいますが、HKQuantityから二重値を得るのに問題があります。 私のコードは次のようになります。HKQuantityをダブルにする - 健康エネルギーから有効エネルギー値を取得する

func getActiveEnergy() { 
    let endDate = NSDate() 
    let startDate = NSCalendar.currentCalendar().dateByAddingUnit(.Month, value: -1, toDate: endDate, options: []) 

    let energySampleType = HKSampleType.quantityTypeForIdentifier(HKQuantityTypeIdentifierActiveEnergyBurned) 
    let predicate = HKQuery.predicateForSamplesWithStartDate(startDate, endDate: endDate, options: .None) 

    print ("start date: ", startDate) 
    print ("end date: ", endDate) 

    let query = HKSampleQuery(sampleType: energySampleType!, predicate: predicate, limit: 0, sortDescriptors: nil, resultsHandler: { 
     (query, results, error) in 
     if results == nil { 
      print("There was an error running the query: \(error)") 
     } 

     dispatch_async(dispatch_get_main_queue()) { 

      for activity in results as! [HKQuantitySample] 
      { 
       self.todayActiveEnergy = activity.quantity.doubleValueForUnit(HKUnit.countUnit()) 
       print(">>>>>", self.todayActiveEnergy) 
      } 

     } 
    }) 
    self.healthKitStore.executeQuery(query) 
} 

私の問題は、この行を次のとおりです。

self.todayActiveEnergy = activity.quantity.doubleValueForUnit(HKUnit.countUnit()) 

確かactivity.quantity戻って正しい値(156キロカロリー)しかし、私はからdouble値を取得しようとすると、それは(上記のように)私が得るlibc++abi.dylib: terminating with uncaught exception of type NSException

これはなぜ起こるかもしれませんか?

+1

エネルギー価値をkcalにしたいのであれば、なぜ 'HKUnit.kilocalorieUnit()'を使わないのですか?私は今あなたのコードをテストすることはできませんが、HealthKitはエネルギーをカウントとして扱うことができないと不平を言うかもしれません。 – OOPer

+0

ああ、私はHKUnit.kilocalorieUnit()を使ってみたが、今は完全に動作する。ありがとうございました! – KeykoYume

+0

あなた自身で回答を投稿するのに時間がかかりますか? – OOPer

答えて

1

彼のコメントのためにOOPerに感謝します。行を次のように変更する:

self.todayActiveEnergy = activity.quantity.doubleValueForUnit(HKUnit.kilocalorieUnit()) 

関連する問題