swift - 当之前在设备上授权 healthkit 访问但否则崩溃时工作正常
问题描述
override func viewDidLoad() {
super.viewDidLoad()
ref = Database.database().reference()
let healthKitTypes: Set = [
// access step count
HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.stepCount)!
]
healthStore.requestAuthorization(toShare: healthKitTypes, read: healthKitTypes) { (_, _) in
print("authorized???")
}
healthStore.requestAuthorization(toShare: healthKitTypes, read: healthKitTypes) { (bool, error) in
if let e = error {
print("oops something went wrong during authorization \(e.localizedDescription)")
} else {
print("User has completed the authorization flow")
}
}
getTodaysSteps { (result) in
print("\(result)")
self.steps = result
DispatchQueue.main.async {
if result == 0 {
self.StepDisplay.text = " You haven't walked"
} else {
self.StepDisplay.text = "\(result)"
}
}
}
getStepHistory()
}
func getStepHistory() {
let calendar = Calendar.current
var interval = DateComponents()
interval.day = 1
// Set the anchor date to Monday at 3:00 a.m.
var anchorComponents = calendar.dateComponents([.day, .month, .year, .weekday], from: Date())
let offset = (7 + (anchorComponents.weekday ?? 0) - 2) % 7
anchorComponents.day = (anchorComponents.day ?? 0) - offset
anchorComponents.hour = 0
anchorComponents.minute = 1
guard let anchorDate = calendar.date(from:anchorComponents) else {
fatalError("*** unable to create a valid date from the given components ***")
}
guard let quantityType = HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.stepCount) else {
fatalError("*** Unable to create a step count type ***")
}
当设备上已经获得授权时,此代码可以正常工作。但是,如果之前没有授权,除非 getStepHistory() 在 viewDidLoad 中被注释掉,否则它不会起作用。我尝试从 getStepHistory() 函数中请求额外授权,但它没有解决问题
解决方案
您需要getStepHistory
在完成块内调用requestAuthorization
它是否已被授权。
healthStore.requestAuthorization(toShare: healthKitTypes, read: healthKitTypes) { (success, error) in
if let e = error {
print("oops something went wrong during authorization \(e.localizedDescription)")
} else if success {
print("User has granted access")
getStepHistory()
} else {
print("User has completed the authorization flow but there is no access")
}
}
推荐阅读
- javascript - Lodash orderBy() 在缩小后给出“TypeError: t is not a function”
- python - 合并熊猫数据框 - 获取 NaN
- c++ - C++ std::vector 赋值方法
- scala - Aws 胶水 scala 如何快速将 DynamicFrame 保存到 athena 表
- php - 如何从 JSON 响应中获取属性
- ios - 对成员“flatMap”的模糊引用
- python - SQL alchemy basequery 对象包含多个类 - 如何对结果进行分页/转换为一个表?
- python - 自动递增的 2 级多索引 pandas
- node.js - 无头 Chrome 在 PM2 中出错
- join - 基于两列比较文件