gpt4 book ai didi

swift - 当之前在设备上授权 healthkit 访问时工作正常,但否则会崩溃

转载 作者:搜寻专家 更新时间:2023-11-01 06:26:12 25 4
gpt4 key购买 nike

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

当授权已在设备上给出时,此代码可以正常工作。但是,如果之前未授权,除非在 viewDidLoad 中将 getStepHistory() 注释掉,否则它将无法工作。我尝试从 getStepHistory() 函数中请求额外的授权,但它没有解决问题

最佳答案

如果已经授权,需要在完成 block 中调用getStepHistoryrequestAuthorization

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

关于swift - 当之前在设备上授权 healthkit 访问时工作正常,但否则会崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54283351/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com