HKObserverQuery 失败,未确定授权

HKObserverQuery Fails with Authorization Not Determined

在尝试为 Healthkit 设置观察者查询时,对于很多用户,我收到 Authorization not Determined 错误。

经过一番研究后,我发现只有在尝试将数据写入(共享)到 Healthkit 时才会发生这样的错误。根据 Apple HK 文档 - 当尝试读取用户未授予权限的数据时,我根本不应该获得任何数据(没有任何错误),就好像没有新数据一样。

这是我用来设置观察者查询的代码:

class func setObserver(healthKitManager manager: HealthKitManager, forType type: HKSampleType?, withPredicateAfterFetching predicate: NSPredicate?) {
    guard type != nil && manager.healthStore != nil else {

        return
    }

    let query = HKObserverQuery.init(sampleType: type!, predicate: nil) { (query, completionHandler, error) in

        guard error == nil else {

            SimpleEvent(name: "HKObserverQuery failed", param: "type:\(type!.identifier), error: \(error!.localizedDescription)").fire()

            return
        }

        let anchoredQuery = HKAnchoredObjectQuery.init(type: type!, predicate: predicate, anchor: manager.getHealthDataAnchor(forType: type!), limit: HKObjectQueryNoLimit, resultsHandler: { (query, results, deletedObjects, newAnchor, error) in

            guard error == nil else {
                SimpleEvent(name: "HKAnchoredQuery failed", param: "type:\(type!.identifier), error: \(error!.localizedDescription)").fire()

                return
            }  

   \ Code that saves the HK Data

            completionHandler()
        })

        manager.healthStore!.execute(anchoredQuery)
    }

    manager.healthStore!.execute(query)
    manager.observerQueries.append(query)
}

错误在 HKObserverQuery failed 事件中被捕获。

正如我提到的,权限请求不应影响数据读取,但无论如何,这里是代码:

func requestAuthorizationToShareTypesAndReadTypes(withSuccess successBlock: @escaping () -> Void, failure failureBlock: @escaping () -> Void) {

    self.healthStore?.requestAuthorization(toShare: writeDataTypes as! Set<HKSampleType>, read: readDataTypes as! Set<HKObjectType>, completion: { (success, error) in

        if !success || error != nil {
            SimpleEvent.init(name: "HK-requestAuthorization", param: error!.localizedDescription)
            NSLog("You didn't allow HealthKit to access these read/write data types. The error was: %@.", error as! NSError);
            failureBlock()
            return;
        }

        self.userHaveBeenPromptWithPermissionsScreenAtLeastOnce = true

        self.enableBackgroundDelivery()

        successBlock()
    })
}

这是我启用后台传送的部分

func enableBackgroundDelivery() {
    for type in self.readDataTypes! {
        if let type = type as? HKSampleType {
            self.enableBackgroundDelivery(forSampleType: type)
        }
    }
}

func enableBackgroundDelivery(forSampleType type:HKSampleType) {
    self.healthStore?.enableBackgroundDelivery(for: type, frequency: HKUpdateFrequency.immediate, withCompletion: { (success, error) in
        if error != nil {
            print(String.init(format: "HK-BackgoundError: error:%@, user: %@, type: %@", error!.localizedDescription, NRManager.shared().username, type.identifier))
        }

    })
}

需要授权才能从 HealthKit 读取数据。如果您收到指示未确定授权的错误,则表示尚未提示用户授权您的应用读取或写入您正在查询的类型的示例。

我通过添加解决了这个问题:

HKObjectType.activitySummaryType()

到我的 HKHealthStore requestAuthorization()

的读取类型