WatchOS从活动应用程序获取信息

时间:2018-06-20 08:25:02

标签: swift apple-watch health-kit watch-os

我想知道是否有一种方法可以从Activity应用程序中获取所有数据:获取消耗的卡路里,距离,运动时间等... 我设法使用此功能获取步骤,但我无法获取其他信息,任何人都可以帮忙吗?

func recentSteps(completion: @escaping (Double, [Double], NSError?) -> ()) {
    let type = HKSampleType.quantityType(forIdentifier: HKQuantityTypeIdentifier.stepCount)

    let date = Date()
    let calendar = Calendar.current
    let curryear = calendar.component(.year, from: date)
    let currmonth = calendar.component(.month, from: date)
    let currday = calendar.component(.day, from: date)
    let last = DateComponents(year: curryear,
                              month: currmonth,
                              day: currday)

    let dates = calendar.date(from: last)!

    let predicate = HKQuery.predicateForSamples(withStart: dates, end: Date(), options: [])
    let query = HKSampleQuery(sampleType: type!, predicate: predicate, limit: 0, sortDescriptors: nil) {
        query, results, error in
        var steps: Double = 0
        var allSteps = [Double]()
        if let myResults = results {
            for result in myResults as! [HKQuantitySample] {
                print(myResults)
                steps += result.quantity.doubleValue(for: HKUnit.count())
                allSteps.append(result.quantity.doubleValue(for: HKUnit.count()))
            }
        }

        completion(steps, allSteps, error as NSError?)

    }

    healthStore.execute(query)
}

1 个答案:

答案 0 :(得分:1)

我认为它可以这样工作,也许将来会对任何人都有帮助,

每天消耗的卡路里:

func energyeUser(completion: @escaping (Double, NSError?) -> ()) {

    if HKHealthStore.isHealthDataAvailable() {
        let energyCount = NSSet(object: HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.activeEnergyBurned) as Any)

        let sharedObjects = NSSet(objects: HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.height) as Any,HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.bodyMass) as Any)

        healthStore.requestAuthorization(toShare: sharedObjects as? Set<HKSampleType>, read: energyCount as? Set<HKObjectType>, completion: { (success, err) in
            self.getStepCount(sender: self)

        })
    }

    let type = HKSampleType.quantityType(forIdentifier: HKQuantityTypeIdentifier.activeEnergyBurned)

    let date = Date()
    let calendar = Calendar.current
    let curryear = calendar.component(.year, from: date)
    let currmonth = calendar.component(.month, from: date)
    let currday = calendar.component(.day, from: date)
    let last = DateComponents(calendar: nil,
                              timeZone: nil,
                              era: nil,
                              year: curryear,
                              month: currmonth,
                              day: currday,
                              hour: nil,
                              minute: nil,
                              second: nil,
                              nanosecond: nil,
                              weekday: nil,
                              weekdayOrdinal: nil,
                              quarter: nil,
                              weekOfMonth: nil,
                              weekOfYear: nil,
                              yearForWeekOfYear: nil)

    let dates = calendar.date(from: last)!

    let predicate = HKQuery.predicateForSamples(withStart: dates, end: Date(), options: [])
    let query = HKStatisticsQuery(quantityType: type!, quantitySamplePredicate: predicate, options: [.cumulativeSum]) { (query, statistics, error) in
        var value: Double = 0

        if error != nil {
            print("something went wrong \(error)")
        } else if let quantity = statistics?.sumQuantity() {
            value = quantity.doubleValue(for: HKUnit.kilocalorie())
        }

        completion(value, error as NSError?)

    }
    healthStore.execute(query)
}

并这样称呼它:

    energyeUser() { energyU, error in
        DispatchQueue.main.sync {
            self.energyCount.setText("\(Int(energyU)) Calories Burnt")
        }
    };

距离:

func distanceUser(completion: @escaping (Double, NSError?) -> ()) {

    if HKHealthStore.isHealthDataAvailable() {
        let distanceCount = NSSet(object: HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.distanceWalkingRunning) as Any)

        let sharedObjects = NSSet(objects: HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.height) as Any,HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.bodyMass) as Any)

        healthStore.requestAuthorization(toShare: sharedObjects as? Set<HKSampleType>, read: distanceCount as? Set<HKObjectType>, completion: { (success, err) in
            self.getStepCount(sender: self)

        })
    }

    let type = HKSampleType.quantityType(forIdentifier: HKQuantityTypeIdentifier.distanceWalkingRunning)

    let date = Date()
    let calendar = Calendar.current
    let curryear = calendar.component(.year, from: date)
    let currmonth = calendar.component(.month, from: date)
    let currday = calendar.component(.day, from: date)
    let last = DateComponents(calendar: nil,
                              timeZone: nil,
                              era: nil,
                              year: curryear,
                              month: currmonth,
                              day: currday,
                              hour: nil,
                              minute: nil,
                              second: nil,
                              nanosecond: nil,
                              weekday: nil,
                              weekdayOrdinal: nil,
                              quarter: nil,
                              weekOfMonth: nil,
                              weekOfYear: nil,
                              yearForWeekOfYear: nil)

    let dates = calendar.date(from: last)!

    let predicate = HKQuery.predicateForSamples(withStart: dates, end: Date(), options: [])
    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.meter())
        }

        completion(value, error as NSError?)

    }
    healthStore.execute(query)
}