使用Swift从HealthKit获取iOS应用程序的骑行时长可以通过以下步骤实现:
import HealthKit
func requestHealthKitAuthorization() {
guard HKHealthStore.isHealthDataAvailable() else {
print("HealthKit is not available on this device.")
return
}
let healthStore = HKHealthStore()
let typesToRead: Set<HKObjectType> = [
HKObjectType.workoutType()
]
healthStore.requestAuthorization(toShare: nil, read: typesToRead) { (success, error) in
if let error = error {
print("Authorization request failed: \(error.localizedDescription)")
} else {
if success {
print("Authorization request succeeded.")
} else {
print("Authorization request denied.")
}
}
}
}
func queryCyclingDuration() {
guard HKHealthStore.isHealthDataAvailable() else {
print("HealthKit is not available on this device.")
return
}
let healthStore = HKHealthStore()
let cyclingType = HKObjectType.workoutType()
let predicate = HKQuery.predicateForWorkouts(with: .cycling)
let sortDescriptor = NSSortDescriptor(key: HKSampleSortIdentifierStartDate, ascending: false)
let query = HKSampleQuery(sampleType: cyclingType, predicate: predicate, limit: 1, sortDescriptors: [sortDescriptor]) { (query, samples, error) in
if let error = error {
print("Query failed: \(error.localizedDescription)")
return
}
guard let samples = samples as? [HKWorkout], let firstSample = samples.first else {
print("No cycling workouts found.")
return
}
let duration = firstSample.duration
print("Cycling duration: \(duration) seconds")
}
healthStore.execute(query)
}
requestHealthKitAuthorization()
queryCyclingDuration()
这样,你就可以使用Swift从HealthKit获取iOS应用程序的骑行时长了。
注意:为了使上述代码正常工作,需要在项目的Info.plist文件中添加对HealthKit的使用描述,以及在项目的Capabilities中启用HealthKit。另外,还需要在Xcode中设置正确的开发者账号和签名配置,以便在真机上运行和测试。
云+社区技术沙龙[第17期]
小程序云开发官方直播课(应用开发实战)
云+社区技术沙龙[第21期]
Elastic 中国开发者大会
云+社区技术沙龙[第11期]
腾讯位置服务技术沙龙
云+社区技术沙龙[第6期]
T-Day
腾讯云GAME-TECH游戏开发者技术沙龙
云+社区技术沙龙[第10期]
领取专属 10元无门槛券
手把手带您无忧上云