我怎样才能获得卡路里?

时间:2017-06-04 11:14:36

标签: ios swift health-kit

enter image description here我有步伐,时间,英里,体重。我怎样才能获得卡路里? 这是一段代码。

 seconds += 1
        let (h,m,s) = secondsToHoursMinutesSeconds(seconds: Int(seconds))
        let secondsQuantity = HKQuantity(unit: HKUnit.second(), doubleValue: Double(s))
        let minutesQuantity = HKQuantity(unit: HKUnit.minute(), doubleValue: Double(m))
        let hoursQuantity = HKQuantity(unit: HKUnit.hour(), doubleValue: Double(h))
        displayTimeLabel.text = ""+hoursQuantity.description+" "+minutesQuantity.description+" "+secondsQuantity.description
        let distanceQuantity = HKQuantity(unit: HKUnit.meter(), doubleValue: distance)
        milesLbl.text = "" + distanceQuantity.description      
        paceLbl.text = ""+String((instantPace*3.6*10).rounded()/10)+" km/h"//"Pace: "+String((distance/seconds*3.6*10).rounded()/10)+" km/h"
  let kg = 75
        caloriesLbl.text = ???

2 个答案:

答案 0 :(得分:0)

以下是我从java example转换的示例代码。它遵循体育活动纲要制定的原则。 大多数运动应用程序使用这些算法来计算代谢活动。

typedef NS_ENUM(NSUInteger, Gender){
    Male,
    Felmale
};

    /**
 * Calculated the energy expenditure for an activity. Adapted from the following website https://sites.google.com/site/compendiumofphysicalactivities/corrected-mets
 *
 * @param height               The height in metres.
 * @param age                  The date of birth.
 * @param weight               The weight of the user.
 * @param gender               The gender of the user.
 * @param durationInSeconds    The duration of the activity in seconds.
 * @param stepsTaken           The steps taken.
 * @param strideLengthInMetres The stride length of the user
 * @return The number of calories burnt (kCal)
 */
- (float)calculateEnergyExpenditureWith:(float) height DOB:(NSDate*) dateOfBirth Weight:(float) weight Gender:(int)gender DurationInSecs:(int) durationInSeconds StepsTaken:(int) stepsTaken StrideLengthInMeters:(float)strideLengthInMetres
{

    float ageCalculated = [self getAgeFromDateOfBirth:dateOfBirth];

    float harrisBenedictRmR = [self
                               convertKilocaloriesToMlKmin:[self
                                                            harrisBenedictRmrWithGender:gender
                                                                                    WeigthKg:weight
                                                                                         Age:ageCalculated
                                                                                    HeightCm:[self convertMetresToCentimetre:height]
                                                            ] WeigthInKg:weight];

    float kmTravelled = [self calculateDistanceTravelledInKM:stepsTaken EntityStrideLength:strideLengthInMetres];
    float hours = durationInSeconds/(3600.0);
    float speedInMph = (kmTravelled/1000.0) / hours;
    float metValue =  [self getMetForActivity:speedInMph];

    float constant = 3.5f;

    float correctedMets = metValue * (constant / harrisBenedictRmR);

    return correctedMets * hours * weight;
}


/**
 * Gets a users age from a date. Only takes into account years.
 *
 * @param age The date of birth.
 * @return The age in years.
 */
- (float) getAgeFromDateOfBirth:(NSDate*) dateOfBirth {
    NSCalendar *calendar = [NSCalendar currentCalendar];
    unsigned unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay;
    NSDateComponents *dateComponentsNow = [calendar components:unitFlags fromDate:[NSDate date]];
    NSDateComponents *dateComponentsBirth = [calendar components:unitFlags fromDate:dateOfBirth];

    if (([dateComponentsNow month] < [dateComponentsBirth month]) ||
        (([dateComponentsNow month] == [dateComponentsBirth month]) && ([dateComponentsNow day] < [dateComponentsBirth day]))) {
        return [dateComponentsNow year] - [dateComponentsBirth year] - 1;
    } else {
        return [dateComponentsNow year] - [dateComponentsBirth year];
    }
}

- (float) convertKilocaloriesToMlKmin:(float)kilocalories WeigthInKg:(float)weightKgs
{
    float kcalMin = kilocalories / 1440.0;
    kcalMin /= 5;

    return ((kcalMin / (weightKgs)) * 1000.0);
}

-(float)convertMetresToCentimetre:(float) metres{
    return metres * 100;
}

- (float) calculateDistanceTravelledInKM:(int)stepsTaken EntityStrideLength:(float) entityStrideLength
{
    return (((float) stepsTaken * entityStrideLength) / 1000);
}


/**
 * Gets the MET value for an activity. Based on https://sites.google.com/site/compendiumofphysicalactivities/Activity-Categories/walking .
 *
 * @param speedInMph The speed in miles per hour
 * @return The met value.
 */

- (float) getMetForActivity:(float) speedInMph
{
    if (speedInMph < 2.0) {
        return 2.0f;
    } else if (speedInMph == 2.0f) {
        return 2.8f;
    } else if (speedInMph > 2.0f  && speedInMph <= 2.7f) {
        return 3.0f;
    } else if (speedInMph > 2.8f && speedInMph <= 3.3f) {
        return 3.5f;
    } else if (speedInMph > 3.4f && speedInMph <= 3.5f) {
        return 4.3f;
    } else if (speedInMph > 3.5f && speedInMph <= 4.0f) {
        return 5.0f;
    } else if (speedInMph > 4.0f && speedInMph <= 4.5f) {
        return 7.0f;
    } else if (speedInMph > 4.5f && speedInMph <= 5.0f) {
        return 8.3f;
    } else if (speedInMph > 5.0f) {
        return 9.8f;
    }
    return 0;
}

/**
 * Calculates the Harris Benedict RMR value for an entity. Based on above calculation for Com
 *
 * @param gender   Users gender.
 * @param weightKg Weight in Kg.
 * @param age      Age in years.
 * @param heightCm Height in CM.
 * @return Harris benedictRMR value.
 */
- (float) harrisBenedictRmrWithGender:(Gender) gender WeigthKg:(float) weightKg Age:(float) age HeightCm:(float)heightCm {
    if (gender == Felmale) {
        return 655.0955f + (1.8496f * heightCm) + (9.5634f * weightKg) - (4.6756f * age);
    } else {
        return 66.4730f + (5.0033f * heightCm) + (13.7516f * weightKg) - (6.7550f * age);
    }

}

答案 1 :(得分:0)

Swift5 版本

    typealias AppHealthKitValueCompletion = ((Double?, Error?)->Void)

    func loadCalory(since start: Date = Date().startOfDay, to end: Date = Date(), completion: @escaping AppHealthKitValueCompletion) {
        guard let type = HKQuantityType.quantityType(forIdentifier: .activeEnergyBurned) else {
            return
        }

        let predicate = HKQuery.predicateForSamples(withStart: start, end: end, options: .strictStartDate)
        let query = HKStatisticsQuery(quantityType: type, quantitySamplePredicate: predicate, options: .cumulativeSum) { (_, result, error) in
            var resultCount = 0.0
            guard let result = result else {
                completion(nil, error)
                return
            }
            
            if let quantity = result.sumQuantity() {
                resultCount = quantity.doubleValue(for: HKUnit.kilocalorie())
            }
            DispatchQueue.main.async {
                completion(resultCount, nil)
            }
        }
        healthStore.execute(query)
    }