IOS 9.2.1,斯威夫特 2.1
我试图在访问 HealthKit 时向用户提供合理的错误消息,并为查询返回 0 条记录。
可能是在选定的时间范围内没有记录,或者可能是用户不允许访问健康中的特定数据集。在这两种情况下,“storage.requestAuthorizationToShareTypes”都提供了“成功”值 true。
有没有办法让 HKHealthKit 商店给我一个代码,表明访问已被禁用?
我的代码如下
谢谢迈克
import Foundation
import HealthKit
// Interface to the HealthKit
class HealthKitIF {
let storage = HKHealthStore()
var stepsEnabled = false
var bgEnabled = false
var hkSupported = false
init () {
self.checkAuthorization()
}
func checkAuthorization () -> Bool {
// Default to assuming that we're authorized
var isEnabled = true
if (NSClassFromString("HKHealthStore") != nil) { hkSupported = true }
// Do we have access to HealthKit on this device?
if ((hkSupported) && (HKHealthStore.isHealthDataAvailable())) {
// We have to request each data type explicitly
// Ask for BG
var readingsSet = Set<HKObjectType>()
readingsSet.insert(HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBloodGlucose)!)
readingsSet.insert(HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierStepCount)!)
storage.requestAuthorizationToShareTypes(nil, readTypes: readingsSet) { (success, error) -> Void in
isEnabled = success
self.bgEnabled = success
}
}
else
{
isEnabled = false
}
return isEnabled
}