2017-02-28 17 views
-1

我正在開發一款應用程序。我想從健康應用中檢索Healthkit數據,但我不知道如何去做。我在互聯網上找不到任何東西。我想從健康應用程序獲取步驟數據。如何檢索Healthkit數據並顯示它?

+0

答案很簡單:做一些研究。然後,如果您有具體問題,請回過頭去問問他們。而當你在這裏:請[旅遊]並看看[幫助]。 – Burki

回答

0

您需要從項目capabilities 使healthkit那麼你會經過authentication過程,那麼你將開始實施query檢索使用HKSampleQuery數據,請遵循this tutorial

的代碼是長被列入在這裏:)

1

有網上很多教程使用healthkit

設置healthkit在您的應用程序和permissio NS遵循這些教程

  1. 遵循官方documentation
  2. Appcoda的HealthKit introduction
  3. 示例應用程序tutorial
  4. Raywenderlich tutorial

例如,如果我們想要取得睡覺分析數據之一,

func retrieveSleepAnalysis() { 

    // first, we define the object type we want 
    if let sleepType = HKObjectType.categoryTypeForIdentifier(HKCategoryTypeIdentifierSleepAnalysis) { 

     // Use a sortDescriptor to get the recent data first 
     let sortDescriptor = NSSortDescriptor(key: HKSampleSortIdentifierEndDate, ascending: false) 

     // we create our query with a block completion to execute 
     let query = HKSampleQuery(sampleType: sleepType, predicate: nil, limit: 30, sortDescriptors: [sortDescriptor]) { (query, tmpResult, error) -> Void in 

      if error != nil { 

       // something happened 
       return 

      } 

      if let result = tmpResult { 

       // do something with my data 
       for item in result { 
        if let sample = item as? HKCategorySample { 
         let value = (sample.value == HKCategoryValueSleepAnalysis.InBed.rawValue) ? "InBed" : "Asleep" 
         print("Healthkit sleep: \(sample.startDate) \(sample.endDate) - value: \(value)") 
        } 
       } 
      } 
     } 

     // finally, we execute our query 
     healthStore.executeQuery(query) 
    } 
} 
6

詢問許可請求允許

if HKHealthStore.isHealthDataAvailable() { 
    var writeDataTypes: Set<AnyHashable> = self.dataTypesToWrite() 
    var readDataTypes: Set<AnyHashable> = self.dataTypesToRead() 
    self.healthStore.requestAuthorization(toShareTypes: writeDataTypes, readTypes: readDataTypes, completion: {(_ success: Bool, _ error: Error) -> Void in 
     if !success { 
      print("You didn't allow HealthKit to access these read/write data types. In your app, try to handle this error gracefully when a user decides not to provide access. The error was: \(error). If you're using a simulator, try it on a device.") 
      return 
     } 
    }) 
} 

寫入數據

func dataTypesToWrite() -> Set<AnyHashable> { 
    var heightType: HKQuantityType? = HKObjectType.quantityType(forIdentifier: .height) 
    var weightType: HKQuantityType? = HKObjectType.quantityType(forIdentifier: .bodyMass) 
    var systolic: HKQuantityType? = HKObjectType.quantityType(forIdentifier: .bloodPressureSystolic) 
    var dystolic: HKQuantityType? = HKObjectType.quantityType(forIdentifier: .bloodPressureDiastolic) 
    return Set<AnyHashable>([heightType, weightType, systolic, dystolic]) 
} 

讀取來自醫療包數據

func dataTypesToRead() -> Set<AnyHashable> { 
    var heightType: HKQuantityType? = HKObjectType.quantityType(forIdentifier: .height) 
    var weightType: HKQuantityType? = HKObjectType.quantityType(forIdentifier: .bodyMass) 
    var systolic: HKQuantityType? = HKObjectType.quantityType(forIdentifier: .bloodPressureSystolic) 
    var dystolic: HKQuantityType? = HKObjectType.quantityType(forIdentifier: .bloodPressureDiastolic) 
    var sleepAnalysis: HKCategoryType? = HKObjectType.categoryType(forIdentifier: .sleepAnalysis) 
    var step: HKQuantityType? = HKObjectType.quantityType(forIdentifier: .stepCount) 
    var walking: HKQuantityType? = HKObjectType.quantityType(forIdentifier: .distanceWalkingRunning) 
    var cycling: HKQuantityType? = HKObjectType.quantityType(forIdentifier: .distanceCycling) 
    var basalEnergyBurned: HKQuantityType? = HKObjectType.quantityType(forIdentifier: .basalEnergyBurned) 

如果你想獲得上週的步數,那麼你可以關注該婁代碼

self.healthStore = HKHealthStore() 
var calendar = Calendar.current 
var interval = DateComponents() 
interval.day = 1 
var anchorComponents: DateComponents? = calendar.dateComponents([.day, .month, .year], from: Date()) 
anchorComponents?.hour = 0 
var anchorDate: Date? = calendar.date(fromComponents: anchorComponents) 
var quantityType: HKQuantityType? = HKObjectType.quantityType(forIdentifier: .stepCount) 
    // Create the query 
var query = HKStatisticsCollectionQuery(quantityType, quantitySamplePredicate: nil, options: HKStatisticsOptionCumulativeSum, anchorDate: anchorDate, intervalComponents: interval) 
// Set the results handler 
query.initialResultsHandler = {(_ query: HKStatisticsCollectionQuery, _ results: HKStatisticsCollection, _ error: Error) -> Void in 
    if error != nil { 
     // Perform proper error handling here 
     print("*** An error occurred while calculating the statistics: \(error?.localizedDescription) ***") 
    } 
    var endDate = Date() 
    var startDate: Date? = calendar.date(byAddingUnit: .day, value: -7, to: endDate, options: 0) 
    // Plot the daily step counts over the past 7 days 
    results.enumerateStatistics(from: startDate, to: endDate, block: {(_ result: HKStatistics, _ stop: Bool) -> Void in 
     var quantity: HKQuantity? = result.sumQuantity() 
     if quantity != nil { 
      var date: Date? = result.startDate 
      var value: Double? = quantity?.doubleValue(forUnit: HKUnit.count()) 
      totalStepsCount = String(format: "%.f", value) 
      DispatchQueue.main.async(execute: {() -> Void in 
       self.calculateStepCountAndShow() 
      }) 
      print("\(date): \(value)") 
     } 
    }) 
} 
self.healthStore.executeQuery(query) 
} 
相關問題