如何在swift中使用HealthKit获得步行和跑步距离

6bc51xsx  于 2023-01-12  发布在  Swift
关注(0)|答案(4)|浏览(127)

我正在制作健康应用程序。我想从Swift中的HealthKit获取walkingRunningDistance。但是,我遇到了一个问题。返回值为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)
    }

    healthAuth.healthStore.executeQuery(query)
}
k10s72fa

k10s72fa1#

您的代码将返回一个值,如果
1.您已向用户请求从HealthKit读取distanceWalkingRunning的权限
1.用户已授予你的应用权限。
如果没有,代码将返回0。
要请求授权,您可以拨打

func requestAuthorization(toShare typesToShare: Set<HKSampleType>?, read typesToRead: Set<HKObjectType>?, completion: @escaping (Bool, Error?) -> Swift.Void)

其中typesToRead包含

let distanceType =  HKSampleType.quantityType(forIdentifier: HKQuantityTypeIdentifier.distanceWalkingRunning)!

我相信使用HKStatisticsQuery或HKStatisticsCollectionQuery会更有效率。以下是一个例子。

guard let type = HKSampleType.quantityType(forIdentifier: .distanceWalkingRunning) else {
    fatalError("Something went wrong retriebing quantity type distanceWalkingRunning")
}
let date =  Date()
let cal = Calendar(identifier: Calendar.Identifier.gregorian)
let newDate = cal.startOfDay(for: date)

let predicate = HKQuery.predicateForSamples(withStart: newDate, end: Date(), options: .strictStartDate)

let query = HKStatisticsQuery(quantityType: type, quantitySamplePredicate: predicate, options: [.cumulativeSum]) { (query, statistics, error) in        
    var value: Double = 0

    if error != nil {
        print("something went wrong")
    } else if let quantity = statistics?.sumQuantity() {
        value = quantity.doubleValue(for: HKUnit.mile())
    }
    DispatchQueue.main.async {
        completion(value)
    }
}
healthStore.execute(query)
aurhwmvo

aurhwmvo2#

适用于Swift 4.1

在项目功能中启用HealthKit并将必要的“隐私-健康共享使用说明”键添加到info.plist文件后...
通过将其添加到ViewController.swift(实际上是在viewDidLoad()函数中),确保您正在请求用户的批准。

let store = HKHealthStore()

    let stepType = HKQuantityType.quantityType(forIdentifier: .stepCount)!
    let woType = HKObjectType.workoutType()

    store.requestAuthorization(toShare: [], read: [stepType, woType], completion: { (isSuccess, error) in
        if isSuccess {
            print("Working")
            self.getSteps()
        } else {
            print("Not working")
        }
    })

然后创建getSteps()函数。

func getSteps() {
    let startDate = Calendar.current.date(bySettingHour: 0, minute: 0, second: 0, of: Date())!

    let endDate = Date()

    print("Collecting workouts between \(startDate) and \(endDate)")

    let predicate = HKQuery.predicateForSamples(withStart: startDate, end: endDate, options: HKQueryOptions.strictEndDate)

    let query = HKSampleQuery(sampleType: HKQuantityType.quantityType(forIdentifier: .distanceWalkingRunning)!, predicate: predicate, limit: HKObjectQueryNoLimit, sortDescriptors: nil) { (query, results, error) in
        for item in results! {
            print(item)
        }
    }

    store.execute(query)
}
dsekswqp

dsekswqp3#

healthStore =[HKHealthStore new];
HKQuantityType *stepType = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];
HKSampleType *sleepType = [HKSampleType categoryTypeForIdentifier:HKCategoryTypeIdentifierSleepAnalysis];
HKQuantityType *walkType = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierDistanceWalkingRunning];
NSArray *arrayType = @[stepType,sleepType,walkType];

[healthStore requestAuthorizationToShareTypes:[NSSet setWithArray:arrayType]
                                    readTypes:[NSSet setWithArray:arrayType] completion:^(BOOL succeeded, NSError *error) {
                                        if (succeeded) {
                                            NSLog(@"Not working");
                                            NSLog(@"error %@",error);
                                        } else {
                                            NSLog(@"Working!");
                                            NSLog(@"error %@",error);
                                        }
                                        [self getStepCount];
                                    }];

上面的方法用于请求访问,下面的方法用于获取计数

-(void)getStepCount{
     NSInteger limit = 0;
     NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd hh:mm:ss"];
    NSDate *startDate = [NSDate  dateWithTimeIntervalSince1970:1372418789];
    // Divided by 1000 (i.e. removed three trailing zeros) ^^^^^^^^
    NSString *formattedDateString = [dateFormatter stringFromDate:startDate];
   // Fri, 28 Jun 2013 11:26:29 GMT
   NSLog(@"start Date: %@", formattedDateString);
   NSDateFormatter *dateFormatter1=[[NSDateFormatter alloc] init];
   [dateFormatter1 setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
   NSLog(@"%@",[dateFormatter1 stringFromDate:[NSDate date]]);
   NSString *dateString =[dateFormatter1 stringFromDate:[NSDate date]];
  NSDate *endDate = [dateFormatter1 dateFromString:dateString];

 NSPredicate *predicate = [HKQuery predicateForSamplesWithStartDate:startDate endDate:endDate options:HKQueryOptionStrictEndDate];

HKSampleQuery *query = [[HKSampleQuery alloc] initWithSampleType:[HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierDistanceWalkingRunning]
                        predicate: predicate
                        limit: limit
                        sortDescriptors: nil
                        resultsHandler:^(HKSampleQuery *query, NSArray* results, NSError *error){
                            dispatch_async(dispatch_get_main_queue(), ^{
                                // sends the data using HTTP
                                int dailyAVG = 0;
                                NSLog(@"result : %@",results);
                                for(HKQuantitySample *samples in results)
                                {
                                    NSLog(@"dailyAVG : %@",samples);
                                }
                                NSLog(@"dailyAVG : %d",dailyAVG);

                                NSLog(@"%@",@"Done");
                            });
                        }];
[healthStore executeQuery:query];

}

kuuvgm7e

kuuvgm7e4#

如果返回零,则代码正确。但是,由于代码处于模拟器视图中,模拟器无法读取距离。要读取距离,请转到模拟器中的健康应用程序,然后选择距离步行和跑步距离,然后按添加数据
然后你的应用可能会读取这些数据。

相关问题