Swift 当healthkit访问以前在设备上获得授权时,工作正常,但在其他情况下崩溃

Swift 当healthkit访问以前在设备上获得授权时,工作正常,但在其他情况下崩溃,swift,healthkit,Swift,Healthkit,当设备上已经给出授权时,此代码可以正常工作。但是,如果之前未授权,则除非在viewDidLoad中注释掉getStepHistory(),否则它将无法工作。我尝试从getStepHistory()函数中请求额外授权,但这并不能解决问题如果已授权,则需要在完成块中调用getStepHistory,以请求授权 override func viewDidLoad() { super.viewDidLoad() ref = Database.database().reference()

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

如果已授权,则需要在完成块中调用
getStepHistory
,以请求授权

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

请求用户的权限

为了请求授权,我们调用

上的requestAuthorization(toShare:,readTypes:,completion:) HKHealthStore实例。此方法接受三个参数:

  • 一组可选的HKSampleType对象
  • 一组可选的HKObjectType对象
  • 具有两个参数的完成处理程序,一个布尔值指示授权请求的结果(成功或失败)和一个可选错误
重要的是要理解,完成处理程序的布尔值并不表示用户是否授予或拒绝访问请求的运行状况数据类型。它仅通知应用程序用户是否响应了应用程序的授权请求。如果用户通过取消授权请求取消表单,则完成处理程序的布尔值将设置为false。

在您的视图中没有加载:

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")
    }
}
healthStore.requestAuthorization(toShare: healthKitTypes, read: healthKitTypes) { (success, error) in
    if let err = error {
        print("Error \(err.localizedDescription)")
    } else if success {
        // Get the Step Count....
        getStepHistory()
    } else {
        print("No access to healthkit data")
    }
}
您也可以尝试使用此函数获取步骤计数:

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")
    }
}
healthStore.requestAuthorization(toShare: healthKitTypes, read: healthKitTypes) { (success, error) in
    if let err = error {
        print("Error \(err.localizedDescription)")
    } else if success {
        // Get the Step Count....
        getStepHistory()
    } else {
        print("No access to healthkit data")
    }
}

您有一个请求授权的完成块。如果用户允许,请在完成块中调用
getStepHistory()
。尝试查找health kit的权限状态。我已经更新了我的答案。