2016-04-11 103 views
4

我的Swift iOS应用程序连接HealthKit以向用户显示当天到目前为止他们采取了多少步骤。大多数情况下,这是成功的。当步骤的唯一来源是iPhone内置计步器功能记录的步骤时,一切正常,我的应用程序显示的步数与Health应用程序的步数相匹配。但是,当我的个人iPhone上有多个数据源时,我的Pebble Time智能手表和iPhone的计步器都会向Health提供步骤 - 我的应用程序出现异常,记录了两者的所有步骤。鉴于iOS健康应用程序根据重复步骤(它可以做到这一点,因为我的iPhone和Pebble报告每60秒就会运行一次健康状况)并显示准确的每日步数,我的应用程序从HealthKit获取的数据包括来自两者的所有步骤来源,造成很大的不准确。Health以不同于HealthKit的方式处理多个步骤源

我怎样才能进入健康应用程序的最终结果,其中的步数是准确的,而不是进入HealthKit的过度膨胀步骤数据流?

UPDATE:这是我用它来获取日常保健数据的代码:

func recentSteps2(completion: (Double, NSError?) ->()) 
    { 

     checkAuthorization() // checkAuthorization just makes sure user is allowing us to access their health data. 
     let type = HKSampleType.quantityTypeForIdentifier(HKQuantityTypeIdentifierStepCount) // The type of data we are requesting 


     let date = NSDate() 
     let cal = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)! 
     let newDate = cal.startOfDayForDate(date) 
     let predicate = HKQuery.predicateForSamplesWithStartDate(newDate, endDate: NSDate(), options: .None) // Our search predicate which will fetch all steps taken today 

     // The actual HealthKit Query which will fetch all of the steps and add them up for us. 
     let query = HKSampleQuery(sampleType: type!, predicate: predicate, limit: 0, sortDescriptors: nil) { query, results, error in 
      var steps: Double = 0 

      if results?.count > 0 
      { 
       for result in results as! [HKQuantitySample] 
       { 
        steps += result.quantity.doubleValueForUnit(HKUnit.countUnit()) 
       } 
      } 

      completion(steps, error) 
     } 

     storage.executeQuery(query) 
    } 
+0

请包含代码片段,演示如何计算用户正在使用的步数。你使用哪种类型的查询? – Allan

+0

@Allan我更新了我的问题以包含我用来计算用户步骤的代码。 – owlswipe

回答

8

你的代码是重复计算步骤,因为它只是一个概括的HKSampleQuery结果。示例查询将返回与给定谓词匹配的所有样本,包括来自多个来源的重叠样本。如果您想用HKSampleQuery准确地计算用户的步数,那么您必须检测重叠的样本并避免对它们进行计数,这会很繁琐且难以正确执行。

健康使用HKStatisticsQueryHKStatisticsCollectionQuery来计算聚合值。这些查询为您计算总和(以及其他总计值),并有效地执行此操作。但最重要的是,他们去重复重叠样本以避免重复计算。

documentation for HKStatisticsQuery包括示例代码。

+0

谢谢!我可以获得更多关于HKStatisticsQuery的信息吗?也许代码示例或教程链接(我搜索谷歌,它很稀疏)? – owlswipe

+0

您是否尝试查看参考文档中的示例代码? https://developer.apple.com/library/ios/documentation/HealthKit/Reference/HKStatisticsQuery_Class/ – Allan