Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • HealthKit Introduction

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 436
    Comment on it

    Hi Readers

    This Tutorial is a brief introduction about the new feature introduced in iOS 8 ,that is, HealthKit.It gives us the way to store and retrieve a user’s health data.

    Before using this HealthKit let us go through the app via which the Healthkit gets the data.The app is “Health”.You will see this app in your iPhone.

    To Enter data in the Health follow the below procedure.

    • Goto the Health App

            

    • Click on Me

    • Click on Edit and Enter your details and click Done.

    • Now like wise Enter other details about yourself

    Now,After Entering the Data.Lets talk about fetching it using HealthKit..

    @ SETUP THE HEALTH KIT(developer's account is mandatory)

    To setup the Health : Open the Capabilities tab in the target editor, and then enable the switch inHealthKit section, as shown in the screenshot below:

     

    @ Create the HealthManager.swift file.

    add

    let healthKitStore:HKHealthStore = HKHealthStore() in the HealthManager Class

     

    • The healthKitStore is the instance of HKHealthStore which is The core of the HealthKit Framework .

    To move further we need to take authorisation permission so that Health App could Share its data with our Application,for this, requestAuthorizationToShareTypes function is used and the code for that is below:

    healthKitStore.requestAuthorizationToShareTypes(hkTypesToWrite, readTypes: hkTypesToRead) { (success, error) -> Void in
    
        if( completion != nil )
        {
          completion(success:success,error:error)
        }
      }
    

    Now the above function will be added in the function func authorizeHealthKit of HealhManager class like below

     func authorize(completion: ((success:Bool, error:NSError!) -> Void)!)
    {
    
      healthKitStore.requestAuthorizationToShareTypes(hkTypesToWrite, readTypes: hkTypesToRead) { (success, error) -> Void in
    
        if( completion != nil )
        {
          completion(success:success,error:error)
        }
      }
    }
    

    Above function should be called for the authorisation process of Health Kit.

    When we RequestAuthorisationToShareTypes we have to tell the What categories we need to read and what categories we need to write about.

    Below code is to set the Types for Read and Write from the HKStore and will be added in the func authorize of HealhManager

     

    // 1. Set the types you want to read from HK Store
        let hkTypesToRead = Set(arrayLiteral: HKObjectType.characteristicTypeForIdentifier(HKCharacteristicTypeIdentifierDateOfBirth)!,
          HKObjectType.characteristicTypeForIdentifier(HKCharacteristicTypeIdentifierBloodType)!,
          HKObjectType.characteristicTypeForIdentifier(HKCharacteristicTypeIdentifierBiologicalSex)!,
          HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBodyMass)!,
          HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeight)!,
          HKObjectType.workoutType()
          )
        
        // 2. Set the types you want to write to HK Store
        let hkTypesToWrite = Set(arrayLiteral:
          HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBodyMassIndex)!,
                  HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierActiveEnergyBurned)!,
          HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDistanceWalkingRunning)!,
          HKQuantityType.workoutType()
          )
    

    Now,after we took to the permission to read and write data in the Health App.We will fetch the data now to use that data on our side.

    To read the data we need to call the below function on the button click and show the data on our end.

    func readCharacteristicData() -> ( age:Int?,  gender:HKBiologicalSexObject?, bloodgroup:HKBloodTypeObject?)
      {
      //  let error:NSError?
    
        let age=readAge()
        var gender:HKBiologicalSexObject?
        var bloodgroup:HKBloodTypeObject?
    
        
        // 2. Read biological sex
        do
        {
        gender =  try healthKitStore.biologicalSex();
        }
        catch let error as NSError {
          print(error.localizedDescription)
        }
        
      
        // 3. Read blood type
        do
        {
       bloodgroup = try healthKitStore.bloodType();
        }
        catch let error as NSError {
          print(error.localizedDescription)
        }
        
        // 4. Return the fetched information 
        return (age, gender, bloodgroup)
      }

     

      func readAge() -> ( Int?)
      {
        //var error:NSError?
        var age:Int?
        
        do {
          let dob = try healthKitStore.dateOfBirth()
          let currentday = NSDate()
        //  let calendar = NSCalendar.currentCalendar()
          let diff = NSCalendar.currentCalendar().components(NSCalendarUnit.Year,    fromDate: dob, toDate: currentday, options: NSCalendarOptions(rawValue: 0))
          age = diff.year
        } catch let error as NSError {
          print(error.localizedDescription)
        }
        
        return (age)
      }
    

    Now if we need to read the data other than the Characteristics :

    The List of Characteristics are:

    1. public let HKCharacteristicTypeIdentifierBiologicalSex: String // NSNumber (HKCharacteristicBiologicalSex)
    2. public let HKCharacteristicTypeIdentifierBloodType: String // NSNumber (HKCharacteristicBloodType)

    3. public let HKCharacteristicTypeIdentifierDateOfBirth: String // NSDate.

    4. public let HKCharacteristicTypeIdentifierFitzpatrickSkinType: String // HKFitzpatrickSkinType

    like in this example we are reading the height and weight of which are not there in the Characteristics and to do this we need to use a query whose base class is HKQuery which is an abstract class with implementations for every type of object. And to read samples HKSampleQuery is used.

    To build a query, you need:

    • A sample to query for (like in this case weight or height).

    •  NSPredicate (optional)

    After creating the query,we just need to call the HKHealthStore method executeQuery() to get the desired results.

    Add the below function to HealthManager.

    func mostRecentSample(typeofsample:HKSampleType , completion: ((HKSample!, NSError!) -> Void)!)
      {
        
        // 1. Build the Predicate
        let past = NSDate.distantPast() 
        let now   = NSDate()
        let predicate = HKQuery.predicateForSamplesWithStartDate(past, endDate:now, options: .None)
        
        // 2. Build the sort descriptor to return the samples in descending order
        let sortDesc = NSSortDescriptor(key:HKSampleSortIdentifierStartDate, ascending: false)
        // 3. we want to limit the number of samples returned by the query to just 1 (the most recent)
        let limit = 1
        
        // 4. Build samples query
        let query = HKSampleQuery(sampleType: typeofsample, predicate: predicate, limit: limit, sortDescriptors: [sortDesc])
          { (query, results, error ) -> Void in
            
            if let queryError = error {
              completion(nil,error)
              return;
            }
            
            // Get the first sample
            let recentSample = results!.first as? HKQuantitySample
            
            // Execute the completion closure
            if completion != nil {
              completion(recentSample,nil)
            }
        }
        // 5. Execute the Query
        self.healthKitStore.executeQuery(query)
      }
    

    After reading the data using Characteristics and HKQuery.Now lets see that how we can save the data.

    To save the data call the below function which will be added in the HealthManager Class.

    func saveData(bmi:Double, date:NSDate ) {
    
      // 1. Create a BMI Sample
      let bType = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBodyMassIndex)
      let bQuantity = HKQuantity(unit: HKUnit.countUnit(), doubleValue: bmi)
      let bSample = HKQuantitySample(type: bType, quantity: bQuantity, startDate: date, endDate: date)
    
      // 2. Save the sample in the store
      healthKitStore.saveObject(bSample, withCompletion: { (success, error) -> Void in
        if( error != nil ) {
          println("Error saving BMI sample: \(error.localizedDescription)")
        } else {
          println("You have successfully saved your sample code")
        }
      })
    }

    In this Code a Sample Object is created using HKQuantitySample class.To create a Sample we have to give proper sampletype like HKQuantityTypeIdentifierBodyMassIndex quantityobject and the start and end date i,e current date and time in both cases.

    And then after creating the sample we will save the object using HKHealthStore‘s method saveObject()

    Now,I end the short HealthKit Introduction

     

    Thanx for Reading

    Keep Coding :)

     

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: