如何解决使用HKActivitySummaryQuery的iOS HealthKit项目-摘要始终为零
目标:从HealthKit中读取我的活动数据(即活动环数据-移动卡路里,锻炼时间和站立时间)
遇到的问题:结果处理程序返回nil HKActivitySummary数组
我尝试过的事情:
我已将HealthKit功能添加到项目中,并添加了两个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)
}
}
解决方法
我认为您缺少权限HKObjectType.activitySummaryType()
请输入以下内容:
let allTypes = Set([
HKObjectType.workoutType(),HKObjectType.quantityType(forIdentifier: .activeEnergyBurned)!,HKObjectType.activitySummaryType()
])
以下是文档:https://developer.apple.com/documentation/healthkit/hkobjecttype/1615319-activitysummarytype
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。