标签: hksamplequery

如何按日期获取Apple健康数据?

Apple运行应用程序按日期提供数据,如下图所示.

在此输入图像描述

通过使用HealthKit我从苹果健康获取步骤数据

let p1 = HKQuery.predicateForSamples(withStart: fromDate, end: Date(), options: .strictStartDate)
let p2 = HKQuery.predicateForObjects(withMetadataKey: HKMetadataKeyWasUserEntered, operatorType: .notEqualTo, value: true)
let timeSortDesriptor = NSSortDescriptor(key: HKSampleSortIdentifierEndDate, ascending: false)//as in health kit entry
let quantityType = HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.stepCount)!
let predicate = HKQuery.predicateForSamples(withStart: fromDate, end: Date(), options: .strictStartDate)
let sourceQuery = HKSourceQuery(sampleType: quantityType, samplePredicate: predicate, completionHandler: { query,sources,error in

if sources?.count != 0  && sources != nil {

                let lastIndex = sources!.count - 1
                var sourcesArray = Array(sources!)
                for i in …
Run Code Online (Sandbox Code Playgroud)

swift healthkit hksamplequery

10
推荐指数
1
解决办法
1200
查看次数

获取HealthKit中每个日期的总步数

什么是获得记录的每一天的总步数的最佳方法HealthKit.使用HKSampleQuery的方法initWithSampleType(见下文),我可以使用设置查询的开始和结束日期NSPredicate,但该方法返回一个每天有许多HKQuantitySamples的数组.

- (instancetype)initWithSampleType:(HKSampleType *)sampleType
                     predicate:(NSPredicate *)predicate
                         limit:(NSUInteger)limit
               sortDescriptors:(NSArray *)sortDescriptors
                resultsHandler:(void (^)(HKSampleQuery *query,
                                         NSArray *results,
                                         NSError *error))resultsHandler
Run Code Online (Sandbox Code Playgroud)

我想我可以查询所有记录的步数并通过数组计算每一天的总步数,但我希望有一个更简单的解决方案,因为会有成千上万的HKSampleQuery对象.有没有办法让initWithSampleType每天返回一个总步数?

objective-c healthkit hksamplequery

8
推荐指数
2
解决办法
9089
查看次数

HealthKit步骤计数器

我正在尝试使用HealthKit的计步器,到目前为止,这就是我所拥有的.它没有失败,但我没有看到任何活动.我错过了什么?

import UIKit
import HealthKit

class ViewController: UIViewController {
    let healthStore: HKHealthStore? = {
        if HKHealthStore.isHealthDataAvailable() {
            return HKHealthStore()
        } else {
            return nil
        }
        }()

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        let endDate = NSDate()
        let startDate = NSCalendar.currentCalendar().dateByAddingUnit(.CalendarUnitMonth, value: -1, toDate: endDate, options: nil)

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

        let query = HKSampleQuery(sampleType: weightSampleType, predicate: predicate, limit: 0, sortDescriptors: …
Run Code Online (Sandbox Code Playgroud)

ios swift healthkit hksamplequery

5
推荐指数
1
解决办法
3417
查看次数

从HealthKit获取昨天的步骤

我正在构建一个供个人使用的应用程序,目前我仍然坚持如何从healthkit准确地获取昨天的步骤.然后从那里,将它放入一个变量(应该很容易,我知道).

我有一个HealthKitManager类,从视图内部调用该函数,然后将其附加到同一视图中的变量.

我已经搜索了大部分的healthKit问题,并且我得到了数据,但我不认为这是准确的数据.我昨天的手机数据是1442步,但它返回了2665步.最重要的是,当我尝试将数据放入变量时,它打印为0.

HealthKitManagerClass

import Foundation
import HealthKit

class HealthKitManager {
let storage = HKHealthStore()

init()
{
    checkAuthorization()
}

func checkAuthorization() -> Bool
{
    // Default to assuming that we're authorized
    var isEnabled = true

    // Do we have access to HealthKit on this device?
    if HKHealthStore.isHealthDataAvailable()
    {
        // We have to request each data type explicitly
        let steps = NSSet(object: HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierStepCount)!)

        // Now we can request authorization for step count data
        storage.requestAuthorizationToShareTypes(nil, readTypes: steps as? Set<HKObjectType>) { (success, error) …
Run Code Online (Sandbox Code Playgroud)

ios swift healthkit swift2 hksamplequery

5
推荐指数
1
解决办法
2008
查看次数

如何从HealthKit获取每日平均步数

我试图显示用户每天的步数.但是真的不知道如何管理这个.

我已经有了这个代码:

let endDate = NSDate()
let startDate = NSCalendar.currentCalendar().dateByAddingUnit(.CalendarUnitMonth, value: -1, toDate: endDate, options: nil)

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

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

        dispatch_async(dispatch_get_main_queue()) {
            var dailyAVG = Int()
            var steps = results as [HKQuantitySample]
            for var i = 0; i < results.count; i++ …
Run Code Online (Sandbox Code Playgroud)

iphone ios swift healthkit hksamplequery

4
推荐指数
2
解决办法
4125
查看次数

运行多个HealthKit样本查询的更好方法是什么?

我有一个场景,我需要从HealthKit中检索多组数据 - 体温,体重和血压.在我可以继续处理之前,我需要全部3,因为它们最终将以PDF格式结束.

我的天真第一种方法是运行一种,然后在HKSampleQuery的resultsHandler中调用第二种方法,然后在结果中调用第三种方法.感觉有点 - 我不知道 - 感觉我错过了什么.

是否有更好的方法或天真的方法是否合理?

ios healthkit hksamplequery

3
推荐指数
3
解决办法
1434
查看次数

如何使用HealthKit快速获取步行和跑步距离

我正在制作Health App。我想walkingRunningDistanceHealthKitSwift中得到。但是,我有一个问题。返回值为0.0mile。

为什么返回值是0英里?

我的代码是这个。

func recentSteps3(completion: (Double, NSError?) -> () ){
    let type = HKSampleType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDistanceWalkingRunning)

    let date = NSDate()

    let cal = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!

    let newDate = cal.startOfDayForDate(date)

    let predicate = HKQuery.predicateForSamplesWithStartDate(newDate, endDate: NSDate(), options: HKQueryOptions.StrictStartDate)

    let query = HKSampleQuery(sampleType: type!, predicate: predicate, limit: HKObjectQueryNoLimit, sortDescriptors: nil) { query, results, error in

        var distance: Double = 0

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

        completion(distance, error) …
Run Code Online (Sandbox Code Playgroud)

swift healthkit hksamplequery

3
推荐指数
1
解决办法
3768
查看次数

通过UUID查找HKObject

在我的应用程序中,用户可以进行锻炼,并且他们会在我的应用程序中列出。如果用户想要删除我的应用程序中的锻炼,我愿意让他也从 HealthKit 中删除它。但我似乎找不到一种方法来HKObject通过它的 uuid 来获取它?!?那不可能吗?导致创建HKSampleQuery和使用uuid == <The-workout-UUID>不起作用。任何说这个键路径(即使 HKObject 有一个 uuid)无效都会崩溃......

ios healthkit hkhealthstore hksamplequery

3
推荐指数
1
解决办法
513
查看次数

如何按小时分组HKStatistics?

我正在尝试从HealthKit中提取步骤数据.

我想创建按小时分组的步骤数据摘要.目前,我可以提取所有所提供的时间范围之间的数据的样本NSPredicateHKSampleQuery.我还可以得到日期范围与之间的步数之和HKStatisticsQuery.

我要问的是,是否有办法按小时对样本或统计数据进行分组.在SQL中我会写这样的东西:

SELECT HOUR(date), SUM(steps) FROM healthkit WHERE date BETWEEN 'blah' AND 'blah' GROUP BY 1;

我是否真的需要24小时31次查询HKStatistics来编写按小时分组的最后一个步骤数据?因为这似乎效率很低,特别是如何resultsHandler实施.

ios ios8 healthkit hksamplequery

2
推荐指数
1
解决办法
2437
查看次数

使用循环运行后台提取时出现NSInternalInconsistencyException

我有这个代码试图为HealthKit数据进行后台获取.当我第一次运行应用程序时,代码工作正常,但如果我手动执行后台提取(使用debug命令),我会抛出一个异常并且出现错误,reason: 'this request has been neutered - you can't call -sendResponse: twice nor after encoding it'我不太清楚为什么.

以下是获取数据的代码:

- (void)fetchNewDataWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {

    if (!self.healthStore) {
        self.healthStore = [HKHealthStore new];
    }

    dataTypes = [NSDictionary dictionaryWithObjectsAndKeys:
                 [NSNumber numberWithInt:1], HKQuantityTypeIdentifierStepCount,
                 [NSNumber numberWithInt:2], HKQuantityTypeIdentifierFlightsClimbed,
                 [NSNumber numberWithInt:3], HKQuantityTypeIdentifierDistanceWalkingRunning,
                 [NSNumber numberWithInt:4], HKQuantityTypeIdentifierDistanceCycling, nil];
    achievementData = [NSMutableDictionary new];

    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDate *startDate = [calendar startOfDayForDate:[NSDate date]];
    NSDate *endDate = [calendar dateByAddingUnit:NSCalendarUnitDay value:1 toDate:startDate options:0];
    NSPredicate *predicate = [HKQuery predicateForSamplesWithStartDate:startDate endDate:endDate options:HKQueryOptionNone];

    for (NSString …
Run Code Online (Sandbox Code Playgroud)

objective-c ios healthkit hksamplequery

2
推荐指数
1
解决办法
1733
查看次数

从 HKSampleQuery 获取最新数据点

我无法使用HKSampleQuery. 我已正确设置应用程序权限,但未HKQuantityTypeIdentifier.bodyMass从 Health 应用程序返回最新的数据条目。

我应该如何使用 获取最新的体重数据点HKSampleQuery

我认为这是因为我设置的 0.0Weight是返回的值,并且我没有得到任何控制台输出readWeight


编辑 1

我的代码包括调试过程如下。

public func readWeight(result: @escaping (Double) -> Void) {
    if (debug){print("Weight")}
    let quantityType = HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.bodyMass)

    let weightQuery = HKSampleQuery(sampleType: quantityType!, predicate: nil, limit: 1, sortDescriptors: nil) {

        query, results, error in

        if (error != nil) {
            if (self.debug){print(error!)}
            result(166.2) //Set as average weight for American
            return
        }

        guard let results = results else {
            if (self.debug){print("No results of query")}
            result(166.2) …
Run Code Online (Sandbox Code Playgroud)

ios swift healthkit hksamplequery

1
推荐指数
1
解决办法
1717
查看次数

标签 统计

healthkit ×11

hksamplequery ×11

ios ×8

swift ×6

objective-c ×2

hkhealthstore ×1

ios8 ×1

iphone ×1

swift2 ×1