Search code examples
iosswifthealthkithksamplequery

After using HealthKit to retrieve SleepAnalysis, I still get this Authorization Not Determined error


I've been using references to this error for a few days now trying to figure out a solution:

[query] Error activating query: Error Domain=com.apple.healthkit Code=5 "Authorization not determined" UserInfo={NSLocalizedDescription=Authorization not determined}

I've been using HealthKit to successfully retrieve sleep data but now I need to retrieve activity data. I set up HealthKit with this function:

let typesToRead = Set([
        HKObjectType.categoryType(forIdentifier: HKCategoryTypeIdentifier.sleepAnalysis)!,
        HKObjectType.categoryType(forIdentifier: HKCategoryTypeIdentifier.appleStandHour)!,
        HKObjectType.characteristicType(forIdentifier: HKCharacteristicTypeIdentifier.dateOfBirth)!,
        HKObjectType.characteristicType(forIdentifier: HKCharacteristicTypeIdentifier.bloodType)!,
        HKObjectType.characteristicType(forIdentifier: HKCharacteristicTypeIdentifier.biologicalSex)!,
        HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.height)!,
        HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.bodyMass)!,
        HKObjectType.workoutType(),
        HKObjectType.activitySummaryType()
        ])

self.healthStore.requestAuthorization(toShare: nil, read: typesToRead) { (sucess, error) -> Void in
        if sucess == false {
            NSLog("Error...")
        }
    }

Then I create my query like:

let query = HKSampleQuery(sampleType: distanceType, predicate: nil, limit: 0, sortDescriptors: [startDateSort]) {
        (sampleQuery, results, error) -> Void in

        if let result = results {
            for item in result {
                if let sample = item as? HKQuantitySample {
                    self.workOutSamples.append(sample)
                }
            }
            print(self.workOutSamples)
        }
    }
    healthStore.execute(query)

I have added Privacy - Health Update Usage Description and Privacy - Health Share Usage Description to info.plist AND my app's capabilities include HealthKit turned on successfully.


Solution

  • Added HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.distanceWalkingRunning)! to typesToRead. My post doesn't show that I used the wrong type: quantityType when creating distanceType.