HKObserverQuery失败,授权未确定

时间:2017-09-10 15:49:24

标签: ios swift authorization health-kit hkobserverquery

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

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

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

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

    })
}

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:0)

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

HKObjectType.activitySummaryType()

到我的 HKHealthStore 的读取类型 requestAuthorization()