Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 我怎样才能得到热量?_Ios_Swift_Healthkit - Fatal编程技术网

Ios 我怎样才能得到热量?

Ios 我怎样才能得到热量?,ios,swift,healthkit,Ios,Swift,Healthkit,我有速度,时间,里程,体重。我怎样才能得到热量? 这是一段代码 seconds += 1 let (h,m,s) = secondsToHoursMinutesSeconds(seconds: Int(seconds)) let secondsQuantity = HKQuantity(unit: HKUnit.second(), doubleValue: Double(s)) let minutesQuantity = HKQuantity(u

我有速度,时间,里程,体重。我怎样才能得到热量? 这是一段代码

 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 = ???

下面是我从java转换而来的示例代码,它遵循了《体育活动纲要》中规定的原则。 大多数练习应用程序都使用这些算法来计算matabolic活动

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);
    }

}
typedef n_ENUM(整数,性别){
男,,
费尔马累
};
/**
*计算活动的能量消耗。改编自以下网站https://sites.google.com/site/compendiumofphysicalactivities/corrected-mets
*
*@param height以米为单位的高度。
*@param age出生日期。
*@param-weight用户的权重。
*@param-gender用户的性别。
*@param durationSecond活动的持续时间(以秒为单位)。
*@param step记录所采取的步骤。
*@param-stridengthintres显示用户的步幅长度
*@返回燃烧的卡路里数(千卡)
*/
-(float)计算能量消耗:(float)身高DOB:(NSDate*)出生体重日期:(float)体重性别:(int)性别持续时间:(int)持续时间秒步长表(int)步长表(float)步长表(float)步长表
{
float Age Calculated=[自getAgeFromDateOfBirth:dateOfBirth];
浮动harrisBenedictRmR=[self
ConvertKilocarestomlkmin:[自身热量]
harrisBenedictRmrWithGender:性别
体重
年龄:年龄计算
HeightCm:[自转换公制厘米:高度]
]WeigthInKg:重量];
float KmTraveled=[自计算的StanceTraveledInKm:stepsTaken EntityRoadLength:RoadLength ThinTrees];
浮动小时=持续时间秒/(3600.0);
浮动速度每小时=(行驶公里/1000.0)/小时;
float metValue=[self getMetForActivity:speedInMph];
浮动常数=3.5f;
浮点数修正后的集合=metValue*(常数/harrisBenedictRmR);
返回修正集*小时*重量;
}
/**
*从日期获取用户年龄。只考虑年份。
*
*@param age出生日期。
*@以年为单位返回年龄。
*/
-(float)getAgeFromDateOfBirth:(NSDate*)dateOfBirth{
NSCalendar*日历=[NSCalendar currentCalendar];
unsigned unitFlags=NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay;
NSDateComponents*dateComponentsNow=[calendar components:unitFlags fromDate:[NSDate date]];
NSDateComponents*dateComponentsBirth=[日历组件:unitFlags fromDate:dateOfBirth];
如果(([dateComponentsNow month]<[dateComponentsBirth month])||
(([dateComponentsNow month]==[dateComponentsBirth month])&&([dateComponentsNow day]<[dateComponentsBirth day])){
返回[dateComponentsNow year]-[dateComponentsBirth year]-1;
}否则{
返回[dateComponentsNow year]-[dateComponentsBirth year];
}
}
-(浮动)换算千卡体重千卡重量公斤
{
浮动kcalMin=千卡/1440.0;
kcalMin/=5;
回报率((千卡分/(重量千克))*1000.0);
}
-(浮动)换算米厘米:(浮动)米{
返回米*100;
}
-(float)CalculatedInstanceTraveledInKM:(int)stepsTaken EntityRoadLength:(float)EntityRoadLength
{
返回(((浮动)步距*实体步距长度)/1000);
}
/**
*获取活动的满足值。基于https://sites.google.com/site/compendiumofphysicalactivities/Activity-Categories/walking .
*
*@param speed inmph以英里/小时为单位的速度
*@返回met值。
*/
-(浮动)getMetForActivity:(浮动)速度每小时
{
如果(车速每小时<2.0){
返回2.0f;
}否则如果(车速英里小时==2.0华氏度){
返回2.8f;
}否则,如果(车速>2.0f和车速2.8f和车速3.4f和车速3.5f和车速4.0f和车速4.5f和车速5.0f){
返回9.8f;
}
返回0;
}
/**
*计算实体的Harris Benedict RMR值。基于上述Com计算
*
*@param性别用户性别。
*@param-weightKg重量,单位为Kg。
*@param年龄以年为单位。
*@param heightCm高度,单位为CM。
*@return-Harris-benedictRMR值。
*/
-(浮球)harrisBenedictRmrWithGender:(性别)性别体重(浮球)体重公斤年龄(浮球)年龄身高厘米(浮球)身高厘米{
如果(性别==男性){
返回655.0955f+(1.8496f*身高厘米)+(9.5634f*体重千克)-(4.6756f*年龄);
}否则{
返回66.4730f+(5.0033f*身高厘米)+(13.7516f*体重千克)-(6.7550f*年龄);
}
}

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)
    }

您是否查看了
HKQuantityTypeIdentifierActivienergyburned
?@Olia\u Pavliuk是的
let healthKitTypesToWrite=Set(数组方向:HKObjectType.quantityType(用于标识符:HKQuantityTypeIdentifier.activeEnergyBurned)!,HKObjectType.quantityType(用于标识符:HKQuantityTypeIdentifier.bodyMass)!,HKObjectType.quantityType(用于标识符:HKQuantityTypeIdentifier.stepCount)!,)