Apple Health Kit 错误域=com.apple.healthkit 代码=5 “未确定授权”

Apple Health Kit Error Domain=com.apple.healthkit Code=5 “Authorization not determined”

在实际尝试访问用户的出生日期和生物性别之前,我已经确定了授权。但它适用于 simulator.but 而不是 iphone 和配对手表。

    let birthdayType = HKQuantityType.characteristicType(forIdentifier: HKCharacteristicTypeIdentifier.dateOfBirth)
    let biologicalSexType = HKQuantityType.characteristicType(forIdentifier: HKCharacteristicTypeIdentifier.biologicalSex)
    let quantityType = HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.heartRate)
    let readDataTypes: Set<HKObjectType> =  [quantityType!, birthdayType!, biologicalSexType!]
    guard HKHealthStore.isHealthDataAvailable() == true else {
        label.setText("not available")
        return
    }

    let readDataTypes: Set<HKObjectType> = self.dataTypesToRead()

    healthStore.requestAuthorization(toShare: nil, read: readDataTypes) { (success, error) -> Void in
        if success == false {
            self.displayNotAllowed()
        }
    }

    var birthDay: Date! = nil
    do {
       birthDay = try self.healthStore.dateOfBirth()
    } catch let error as NSError{
        print("Either an error occured fetching the user's age information or none has been stored yet. \(error)")
        return -1
    }
    var biologicalSex:HKBiologicalSexObject! = nil
    do {
        try biologicalSex = self.healthStore.biologicalSex()
    }catch let error as NSError{
        print("Failed to read the biologicalSex! \(error)")
    }

这是并发问题,不是 HealthKit 问题。

requestAuthorization 可能会显示一个对话框并在后台进程中为您提供结果。

你必须等待 requestAuthorization 的答案才能继续阅读 birthday 和 biologicalSex。