HEALTH_KIT

Workout App explaining Activities

- Swimming
- Walking/Runnig
- FLightsClimed
- Steps
import UIKit
import HealthKit

class HealthKitManager: NSObject {
    
    class var sharedInstance: HealthKitManager{
        struct Singleton {
            static let instance = HealthKitManager()
        }
        return Singleton.instance
    }
    
    let healthStore: HKHealthStore? = {
        
        if HKHealthStore.isHealthDataAvailable(){
            return HKHealthStore()
        }else{
            return nil
        }
    }()
    
    let stepsCount = HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.stepCount)
    let stepsUnit  = HKUnit.count()
    
    let distanceWalkingRunning = HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.distanceWalkingRunning)
    let distanceSwimming = HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.distanceSwimming)
    
    let distanceUnit =  HKUnit.mile()
    
    let flightsClimbed = HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.flightsClimbed)
    let flightClimbedUnit  = HKUnit.count()


}

import UIKit
import HealthKit

class DetailViewController: UIViewController {
    
    let healthKitManager = HealthKitManager.sharedInstance
    var workoutType: WorkoutTypes = .RunningWalking

    var steps = [HKQuantitySample]()
    var floors = [HKQuantitySample]()
    var distance: String!
    
    @IBOutlet weak var tableView: UITableView!
    
    let dateFormatter: DateFormatter = {
        let formatter = DateFormatter()
        formatter.dateStyle = .short
        return formatter
    }()
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.title = self.workoutType.rawValue
         requestForHealthKitAuthorization()
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
    
    func requestForHealthKitAuthorization(){
        
        let quantityObject = setHealthKitUnitType()
        let dataTypesToRead = NSSet(object:quantityObject!) as? Set<HKObjectType>
        
        healthKitManager.healthStore?.requestAuthorization(toShare: nil, read: dataTypesToRead, completion: { [unowned self] (success, error) in
            
            if success{
                self.getHealthKitValues()
            }else{
                print(error.debugDescription)
            }
        })
    }
    
    func setHealthKitUnitType() -> Any?{
        
        switch self.workoutType {
        case .Steps:
            return healthKitManager.stepsCount
        case .RunningWalking:
            return healthKitManager.distanceWalkingRunning
        case .FlightsClimbed:
            return healthKitManager.flightsClimbed
        case .Swimming:
            return healthKitManager.distanceSwimming
        }
    }
    
    func getHealthKitValues(){
        
        switch self.workoutType {
        case .Steps:
            self.queryTodaysStepsSum()
            self.querySteps()
            break
        case .RunningWalking:
            self.readDistanceWalkingRunningData()
        case .FlightsClimbed:
            self.totalFlightsClimbed()
            self.readFloors()
            break
        case .Swimming:
            self.readSwimmingData()
            break
        }
    }
    
}
    

extension DetailViewController:UITableViewDataSource,UITableViewDelegate{
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        switch self.workoutType {
        case .Steps:
            return self.steps.count
        case .FlightsClimbed:
            return self.floors.count
        case .RunningWalking ,.Swimming:
            return 1
        }
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "stepsCellId")! as UITableViewCell
        
        switch self.workoutType {
        case .Steps:
            
            let step = steps[indexPath.row]
            let numberOfSteps = Int(step.quantity.doubleValue(for: healthKitManager.stepsUnit))
            
            cell.textLabel?.text = "\(numberOfSteps) steps"
            cell.detailTextLabel?.text = dateFormatter.string(from: step.startDate)
            break
            
        case .FlightsClimbed:
            
            let step = floors[indexPath.row]
            let numberOfSteps = Int(step.quantity.doubleValue(for: healthKitManager.flightClimbedUnit))
            
            cell.textLabel?.text = "\(numberOfSteps) floors"
            cell.detailTextLabel?.text = dateFormatter.string(from: step.startDate)
            break
            
        case .RunningWalking ,.Swimming:
            cell.textLabel?.text = distance
            cell.detailTextLabel?.text = ""

            break
        }
        
        return cell
    }
    
}
func queryTodaysStepsSum(){
        
        let now = Date()
        let startOfDay = Calendar.current.startOfDay(for: now)
        let predicate = HKQuery.predicateForSamples(withStart: startOfDay, end: now, options: .strictStartDate)
        
        let sumOption = HKStatisticsOptions.cumulativeSum
        let statisticsSumQuery = HKStatisticsQuery(quantityType: healthKitManager.stepsCount!,
                                                   quantitySamplePredicate: predicate,
                                                   options: sumOption) { (query, result, error) in
                                                    
                                                    if let sumQuantity = result?.sumQuantity(){
                                                        
                                                        DispatchQueue.main.async {
                                                            let headerView = self.tableView.dequeueReusableCell(withIdentifier: "totalStepsCell")! as UITableViewCell
                                                            
                                                            let numberOfSteps = Int(sumQuantity.doubleValue(for: self.healthKitManager.stepsUnit))
                                                            headerView.textLabel?.text = " \(numberOfSteps) STEPS"
                                                            self.tableView.tableHeaderView = headerView
                                                        }
                                                    }
        }
        healthKitManager.healthStore?.execute(statisticsSumQuery)
    }
    
    func querySteps(){
        
        let now = Date()
        let startOfDay = Calendar.current.startOfDay(for: now)
        let predicate = HKQuery.predicateForSamples(withStart: startOfDay, end: now, options: .strictStartDate)
        
        let sampleQuery = HKSampleQuery(sampleType: healthKitManager.stepsCount!,
                                        predicate: predicate,
                                        limit: 20,
                                        sortDescriptors: nil) { [weak self](query,results, error) in
                                            
                                            if let results = results as? [HKQuantitySample]{
                                                self?.steps = results
                                                
                                                DispatchQueue.main.async {
                                                    self?.tableView.reloadData()
                                                }
                                            }
        }
        
        healthKitManager.healthStore?.execute(sampleQuery)
    }
func readDistanceWalkingRunningData() {
        
        var walkingAVG = 0.0;
        
        let now = Date()
        let startOfDay = Calendar.current.startOfDay(for: now)
        let predicate = HKQuery.predicateForSamples(withStart: startOfDay, end: now, options: .strictStartDate)
        
        let sampleQuery = HKSampleQuery(sampleType: healthKitManager.distanceWalkingRunning!,
                                        predicate: predicate,
                                        limit: HKObjectQueryNoLimit,
                                        sortDescriptors: nil) { [weak self](query,results, error) in
                                            
                                            if let results = results as? [HKQuantitySample]{
                                                
                                                for samples in results{
                                                    walkingAVG += samples.quantity.doubleValue(for: (self?.healthKitManager.distanceUnit)!)
                                                }
                                                DispatchQueue.main.async {
                                                    self?.distance = String(format:"%f miles",walkingAVG)
                                                    self?.tableView.reloadData()
                                                }
                                            }
        }
        healthKitManager.healthStore?.execute(sampleQuery)
    }
func readSwimmingData() {
        
        var walkingAVG = 0.0;
        
        let now = Date()
        let startOfDay = Calendar.current.startOfDay(for: now)
        let predicate = HKQuery.predicateForSamples(withStart: startOfDay, end: now, options: .strictStartDate)
        
        let sampleQuery = HKSampleQuery(sampleType: healthKitManager.distanceSwimming!,
                                        predicate: predicate,
                                        limit: HKObjectQueryNoLimit,
                                        sortDescriptors: nil) { [weak self](query,results, error) in
                                            
                                            if let results = results as? [HKQuantitySample]{
                                                
                                                for samples in results{
                                                    walkingAVG += samples.quantity.doubleValue(for: (self?.healthKitManager.distanceUnit)!)
                                                }
                                                DispatchQueue.main.async {
                                                    self?.distance = String(format:"%f miles",walkingAVG)
                                                    self?.tableView.reloadData()

                                                }
                                            }
        }
        healthKitManager.healthStore?.execute(sampleQuery)
    }
func totalFlightsClimbed() {
        
        let now = Date()
        let startOfDay = Calendar.current.startOfDay(for: now)
        let predicate = HKQuery.predicateForSamples(withStart: startOfDay, end: now, options: .strictStartDate)
        
        let sumOption = HKStatisticsOptions.cumulativeSum
        let statisticsSumQuery = HKStatisticsQuery(quantityType: healthKitManager.flightsClimbed!,
                                                   quantitySamplePredicate: predicate,
                                                   options: sumOption) { (query, result, error) in
                                                    
                                                    if let sumQuantity = result?.sumQuantity(){
                                                        
                                                        DispatchQueue.main.async {
                                                            let headerView = self.tableView.dequeueReusableCell(withIdentifier: "totalStepsCell")! as UITableViewCell
                                                            
                                                            let numberOfSteps = Int(sumQuantity.doubleValue(for: self.healthKitManager.flightClimbedUnit))
                                                            headerView.textLabel?.text = " \(numberOfSteps) FLOORS"
                                                            self.tableView.tableHeaderView = headerView
                                                        }
                                                    }
        }
        healthKitManager.healthStore?.execute(statisticsSumQuery)
    }
    
    func readFloors(){
        
        let now = Date()
        let startOfDay = Calendar.current.startOfDay(for: now)
        let predicate = HKQuery.predicateForSamples(withStart: startOfDay, end: now, options: .strictStartDate)
        
        let sampleQuery = HKSampleQuery(sampleType: healthKitManager.flightsClimbed!,
                                        predicate: predicate,
                                        limit: 20,
                                        sortDescriptors: nil) { [weak self](query,results, error) in
                                            
                                            if let results = results as? [HKQuantitySample]{
                                                self?.floors = results
                                                
                                                DispatchQueue.main.async {
                                                    self?.tableView.reloadData()
                                                }
                                            }
        }
        
        healthKitManager.healthStore?.execute(sampleQuery)
    }

Comments

Popular Posts