【发布时间】:2020-09-16 04:58:32
【问题描述】:
目标:从 HealthKit 中读取我的活动数据(即活动环数据 - 移动卡路里、锻炼分钟数和站立时间)
遇到的问题:结果处理程序返回“nil”HKActivitySummary 数组
我的尝试:
我在项目中添加了 HealthKit Capability 并添加了两个 info.plist 要求:
隐私 - 健康共享使用说明
隐私 - 健康更新使用说明
并确保当 iPhone 中出现 HealthKit 的权限请求弹出窗口时,我点击了“全部允许”以获得权限。
我还记录了很多周的活动数据,所以应该没问题。
如何检索 HKActivitySummary 对象数组,以便在我的 iOS 应用程序中复制环。
我的代码:
override func viewDidLoad() {
super.viewDidLoad()
startQueryForActivitySummary(view: self.view)
}
func startQueryForActivitySummary(view: UIView) {
let calendar = NSCalendar.current
let endDate = Date()
guard let startDate = calendar.date(byAdding: .day, value: -7, to: endDate) else {
fatalError("*** Unable to create the start date ***")
}
let units: Set<Calendar.Component> = [.day, .month, .year, .era]
var startDateComponents = calendar.dateComponents(units, from: startDate)
startDateComponents.calendar = calendar
var endDateComponents = calendar.dateComponents(units, from: endDate)
endDateComponents.calendar = calendar
let queryPredicate = HKQuery.predicate(forActivitySummariesBetweenStart: startDateComponents,
end: endDateComponents)
let query = HKActivitySummaryQuery(predicate: queryPredicate) { (query, summaries, error) -> Void in
if let summaries = summaries { // print(summaries) before this line will always return nil.
if let summary = summaries.first {
let activeEnergyBurned = summary.activeEnergyBurned.doubleValue(for: HKUnit.kilocalorie())
let activeEnergyBurnedGoal = summary.activeEnergyBurnedGoal.doubleValue(for: HKUnit.kilocalorie())
let activeEnergyBurnGoalPercent = round(activeEnergyBurned/activeEnergyBurnedGoal)
let frame = CGRect(x: 0, y: 0, width: 200, height: 200)
let ringView = HKActivityRingView(frame: frame)
view.addSubview(ringView)
ringView.setActivitySummary(summary, animated: true)
}
}
}
let allTypes = Set([HKObjectType.workoutType(),
HKObjectType.quantityType(forIdentifier: .activeEnergyBurned)!])
let healthStore = HKHealthStore()
healthStore.requestAuthorization(toShare: allTypes, read: allTypes) { (success, error) in
healthStore.execute(query)
}
}
【问题讨论】:
-
我复制了您的代码,但身份验证似乎没有调用。我和你一样一无所获。我将身份验证移到了这段代码之外,当身份验证运行时,我不再得到零。但我仍然得到 0 个摘要,并且像你一样,我有应该返回的数据。抱歉,没有太大帮助。
-
@johnelemans 对您的尝试有所帮助!我想知道它是否与我必须请求授权的数据有关。我不确定我是否应该有一个数组来请求用户拥有的每个数据健康点。看起来很奇怪,但任何人的澄清都会有所帮助!谢谢