2016-08-30 69 views
3

我正在使用Xcode 8 beta 6,並且正在請求訪問Health App。當完成處理程序在我的代碼中返回 - success時,請求授權的方法requestAuthorization(toShare:read:completion:)始終會生成true。即使我拒絕模擬器中的所有內容,我也會收到true。 這是我處理授權的代碼。是我的代碼錯了,或者這是一個Xcode錯誤?HealthKit - requestAuthorization(toShare:read:completion :)總是成功

import Foundation 
import HealthKit 

class HealthManager { 
    private let healthStore = HKHealthStore() 

    class var sharedInstance: HealthManager { 
     struct Singleton { 
      static let instance = HealthManager() 
     } 
     return Singleton.instance 
    } 

    private var isAuthorized: Bool? = false 

    func authorizeHealthKit(completion: ((_ success: Bool) -> Void)!) { 
     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)!] 

     guard HKHealthStore.isHealthDataAvailable() else { 
      completion(false) 
      return 
     } 

     // Request Authorization 
     healthStore.requestAuthorization(toShare: writableTypes, read: readableTypes) { (success, error) in 

      if success { 
       completion(true) 
       self.isAuthorized = true 
      } else { 
       completion(false) 
       self.isAuthorized = false 
       print("error authorizating HealthStore. You're propably on iPad \(error?.localizedDescription)") 
      } 
     } 
    } 
} 

感謝您的幫助!

+1

你可以發佈您的最終代碼是什麼樣子? – Adrian

回答

6

你錯誤地解釋了那個成功標誌的含義。 YES表示權限屏幕已成功顯示,NO表示顯示權限屏幕時出現錯誤。從Apple的HealthKit文檔:

一個布爾值,指示請求是否已成功處理。該值不表示權限是否被實際授予。如果處理請求時發生錯誤,則此參數爲NO;否則爲YES。

如果要檢查是否有權寫入數據,則需要使用authorizationStatus(for:),但請注意,您無法確定讀取數據的授權。

此方法檢查用於保存數據的授權狀態。

爲幫助防止敏感健康信息可能泄漏,您的應用無法確定用戶是否授予讀取數據的權限。如果您沒有獲得權限,則看起來好像在HealthKit商店中沒有所請求類型的數據。如果您的應用具有共享權限但未具有讀取權限,則只會看到應用已寫入商店的數據。其他來源的數據仍然隱藏。

文檔是在這裏:https://developer.apple.com/library/ios/documentation/HealthKit/Reference/HKHealthStore_Class/index.html

+0

謝謝。就是這樣。在保存示例之前,我應該使用'authorizationStatus(for :)'! – heikomania