Skip to content

Instantly share code, notes, and snippets.

@DonMag
Created November 9, 2017 16:10
Show Gist options
  • Select an option

  • Save DonMag/86e275c2b7199754907067354a4f9aef to your computer and use it in GitHub Desktop.

Select an option

Save DonMag/86e275c2b7199754907067354a4f9aef to your computer and use it in GitHub Desktop.
//
// HealthViewController.swift
// IBScratch
//
// Created by Don Mag on 11/9/17.
// Copyright © 2017 DonMag. All rights reserved.
//
import UIKit
import HealthKit
class HealthKitManager {
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)
}
class HealthViewController: UIViewController {
var theStepsArray = [Int]()
fileprivate let healthKitManager = HealthKitManager.sharedInstance
override func viewDidLoad() {
super.viewDidLoad()
requestHealthKitAuthorization()
}
}
private extension HealthViewController {
func todayTotalSteps () -> Void{
let healthStore: HKHealthStore? = {
if HKHealthStore.isHealthDataAvailable() {
return HKHealthStore()
} else {
return nil
}
}()
let calendar = NSCalendar.current
let interval = NSDateComponents()
interval.day = 1
var anchorComponents = calendar.dateComponents([.day, .month, .year], from: NSDate() as Date)
anchorComponents.hour = 0
let anchorDate = calendar.date(from: anchorComponents)
guard let stepsCount = healthKitManager.stepsCount else {
fatalError("*** Unable to create a step count type ***")
}
// Define 1-day intervals starting from 0:00
let stepsQuery = HKStatisticsCollectionQuery(quantityType: stepsCount, quantitySamplePredicate: nil, options: .cumulativeSum, anchorDate: anchorDate!, intervalComponents: interval as DateComponents)
stepsQuery.initialResultsHandler = { query, results, error in
let endDate = NSDate()
let startDate = calendar.date(byAdding: .day, value: -365, to: endDate as Date, wrappingComponents: false)
if let myResults = results{
myResults.enumerateStatistics(from: startDate!, to: endDate as Date) { statistics, stop in
if let quantity = statistics.sumQuantity(){
let steps = quantity.doubleValue(for: HKUnit.count())
// append to array
self.theStepsArray.append(Int(steps))
// let date = statistics.startDate
// print(date, "we have steps for this date")
}
else
{
self.theStepsArray.append(0)
// let date = statistics.startDate
// print(date, "no steps for this date")
}
} //end block
} //end if leta
// here we have processed all the results
print(self.theStepsArray)
print()
print("Array size is now:", self.theStepsArray.count)
// NOTE: If you are going to update the UI do it in the main thread
DispatchQueue.main.async {
//update UI components
}
}
healthStore?.execute(stepsQuery)
}
func requestHealthKitAuthorization() {
let dataTypesToRead = NSSet(objects: healthKitManager.stepsCount as Any)
healthKitManager.healthStore?.requestAuthorization(toShare: nil, read: dataTypesToRead as? Set<HKObjectType>, completion: { [unowned self] (success, error) in
if success {
self.todayTotalSteps()
} else {
print(error.debugDescription)
}
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment