我用的类:
HealthKit需要先判断权限,如果权限通过了,才可以获取其他的,所有的代码都需要在authorizeHealthKit方法成功之后,才可以调用,HealthKit并不是说我获取一个权限就好了,所有的步数,获取体重都是单独的,所有的权限都需要单独获取
- 首先,项目开启HealthKit
判断和申请权限,manager的代码:
import HealthKit class HealthManager: NSObject { let healthKitStore:HKHealthStore = HKHealthStore() //这里是获取权限 func authorizeHealthKit(completion: ((_ success:Bool, _ error:NSError!) -> Void)!) { // 需要获取的数据 出生年月 血型 性别 体重 身高 let healthKitTypesToRead = NSSet(array:[ HKObjectType.characteristicType(forIdentifier: HKCharacteristicTypeIdentifier.dateOfBirth) as Any , HKObjectType.characteristicType(forIdentifier: HKCharacteristicTypeIdentifier.bloodType) as Any, HKObjectType.characteristicType(forIdentifier: HKCharacteristicTypeIdentifier.biologicalSex) as Any, HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.bodyMass) as Any, HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.height) as Any, HKObjectType.workoutType() ]) //需要写入的数据 let healthKitTypesToWrite = NSSet(array:[ HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.bodyMassIndex) as Any, HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.activeEnergyBurned) as Any, HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.distanceWalkingRunning) as Any, HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.stepCount) as Any, HKQuantityType.workoutType() ]) // 健康是否可以使用 if !HKHealthStore.isHealthDataAvailable() { let error = NSError(domain: "com.raywenderlich.tutorials.healthkit", code: 2, userInfo: [NSLocalizedDescriptionKey:"HealthKit is not available in this Device"]) if( completion != nil ) { completion(false, error) } return; } // 授权 healthKitStore.requestAuthorization(toShare: healthKitTypesToWrite as? Set<HKSampleType>, read: healthKitTypesToRead as? Set<HKObjectType>) { (success, error) in if( completion != nil ) { completion(success, error as NSError?) } }; } //获取身高 func getHeight(completion: ((_ success:Bool,_ height:Double, _ error:NSError!) -> Void)!){ //出事话一个HKSampleSortIdentifierEndDate为key的降序,这样会得到一个用户存储在health sore中的最新的的体重取样 let sort:NSSortDescriptor = NSSortDescriptor.init(key: HKSampleSortIdentifierEndDate, ascending: false) var query = HKSampleQuery.init(sampleType: HKSampleType.quantityType(forIdentifier: .height)!, predicate: nil, limit: 1, sortDescriptors: [sort], resultsHandler: { (query, results, error) in if(results?.count ?? 0 > 0){ let sameple = results?[0] as! HKQuantitySample let height = sameple.quantity.doubleValue(for: HKUnit.meter()) completion(true,height,nil) }else{ completion(false,0,error as NSError?) } }) healthKitStore.execute(query) } //获取步数 func getStepCount(){ //出话一个HKSampleSortIdentifierEndDate为key的降序,这样会得到一个用户存储在health sore中的最新的数据取样 let sort:NSSortDescriptor = NSSortDescriptor.init(key: HKSampleSortIdentifierEndDate, ascending: false) // let predicate = HKQuery.predicateForSamples(withStart: nil, end: NSDate.init() as Date, options: .strictStartDate) var query = HKSampleQuery.init(sampleType: HKSampleType.quantityType(forIdentifier: .stepCount)!, predicate: nil, limit: HKObjectQueryNoLimit, sortDescriptors: [sort], resultsHandler: { (query, results, error) in print("-----------\(results)") for sameple in results ?? []{ let model = sameple as! HKQuantitySample print("----------- \(model.startDate) \( model.startDate) \( model.quantity)") } }) healthKitStore.execute(query) } }
ViewController代码
class ViewController: UIViewController { let manager:HealthManager = HealthManager.init() override func viewDidLoad() { super.viewDidLoad() manager.authorizeHealthKit { (success, error) in if(success){ self.getInfo(); //获取数据 self.getHeight(); }else{ print("--------------------\(String(describing: error))") } } } func getInfo(){ let healthKitStore = HKHealthStore() do { let unwrappedBiologicalSex = try healthKitStore.biologicalSex() switch unwrappedBiologicalSex.biologicalSex { case .notSet: print("性别:没有设置") break case .female: print("性别:女") break case .male: print("性别:男") break default: print("性别:其他") break } let birthDate = try healthKitStore.dateOfBirthComponents() print("出生日期:\(birthDate.year!)年\(birthDate.month!)月\(birthDate.day!)日") } catch let error { print("没有权限获取该数据\(error)") } } func getHeight(){ // manager.getHeight { (success, height, error) in // print("这里是身高:\(height)") // } manager.getStepCount() } }