WatchOS 从 Activity 个应用获取信息

WatchOS get info from Activity app

我想知道是否有办法从 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)
}

我是这样工作的,也许这对以后的任何人都有帮助,

每天燃烧的卡路里:

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