簡體   English   中英

迅捷:如何請求HealtKit許可?

[英]swift: How to ask for HealtKit permission?

我希望我的iOS應用程序可以與Apple的HealKit進行交互。

要請求授權,我使用以下幾行:

public func requestHealthkit() {
    let healthStore = HKHealthStore()
    var shareTypes = Set<HKSampleType>()
    shareTypes.insert(HKSampleType.workoutType())
    var readTypes = Set<HKObjectType>()
    readTypes.insert(HKObjectType.workoutType())

    healthStore.requestAuthorization(toShare: shareTypes, read: readTypes) { (success, error) -> Void in
        if success {
            print("[HealthKit] request Authorization succeed!")
        } else {
            print("[HealthKit] request Authorization failed!")
        }
        if let error = error { print("[HealthKit] An error occurred: \(error)") }
    }
} 

編輯1(使用這種方式也將無效)

healthStore.requestAuthorization(toShare: shareTypes, read: readTypes) { (success, error) in
   print("I'm not called. However! :p")
}

編輯2(這是我的info.plist) :我已將NSHealthUpdateUsageDescription添加到info.plist -file並打開了運行狀況工具包功能。

圖片1

這些是我的功能設置:

圖片2

但是調用函數requestHealthkit() 不會起作用,也不會產生任何錯誤消息或log ,只是-> NOTHING。

這是請求HealthKit授權的正確方法,還是我做錯了什么? 2.場景很可能是

幫助將不勝感激,謝謝。

我已經成功提交了申請表。 看看另一個問題( HealthKit-requestAuthorization(toShare:read:completion :)總是成功 )。 看起來您的集合中使用的類型不是預期的。

override func viewDidAppear(_ animated: Bool) {
    if HKHealthStore.isHealthDataAvailable() {
        if let hk = (UIApplication.shared.delegate as! AppDelegate?)?.healthStore {
            self.requestHealthkit(hk)
        }
    }
}

private func requestHealthkit(_ healthStore:HKHealthStore) {
    let writableTypes: Set<HKSampleType> = [
        HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.distanceWalkingRunning)!,
        HKWorkoutType.workoutType(),
        HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.stepCount)!,
        HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.activeEnergyBurned)!,
        HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.heartRate)!
    ]
    let readableTypes: Set<HKSampleType> = [
        HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.distanceWalkingRunning)!,
        HKWorkoutType.workoutType(),
        HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.stepCount)!,
        HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.activeEnergyBurned)!,
        HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.heartRate)!
    ]


    healthStore.requestAuthorization(toShare: writableTypes, read: readableTypes) { (success, error) -> Void in
        if success {
            print("[HealthKit] request Authorization succeed!")
        } else {
            print("[HealthKit] request Authorization failed!")
        }
        if let error = error { print("[HealthKit] An error occurred: \(error)") }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM