Skip to content

HealthStoreManager (Deprecated)

S025_신명섭 edited this page Dec 1, 2021 · 1 revision

HealthStoreManager (Deprecated)

import Foundation
import HealthKit

final class HealthStoreManager {

    static let shared = HealthStoreManager()

    private var healthStore: HKHealthStore?

    private init() {
        if HKHealthStore.isHealthDataAvailable() {
            healthStore = HKHealthStore()
            
        } else {
            return
        }
    }

    func requestAuthorization() {
        guard let activeEnergyBurned     = HKSampleType.quantityType(forIdentifier: .activeEnergyBurned),
              let distanceWalkingRunning = HKSampleType.quantityType(forIdentifier: .distanceWalkingRunning),
              let stepCount              = HKSampleType.quantityType(forIdentifier: .stepCount) else { return }

        let shareTypes = Set([activeEnergyBurned, distanceWalkingRunning, stepCount])
        let readTypes  = Set([activeEnergyBurned, distanceWalkingRunning, stepCount])

        healthStore?.requestAuthorization(toShare: shareTypes, read: readTypes) { (success, error) in
            guard error != nil,
                  success else { return }

        }
    }

    func requestStatisticsCollectionQuery(type: HKQuantityType, predicate: NSPredicate, interval: DateComponents, anchorDate: Date, completion: @escaping (HKStatisticsCollection) -> Void) {
        let query = HKStatisticsCollectionQuery(
            quantityType: type,
            quantitySamplePredicate: predicate,
            options: .cumulativeSum,
            anchorDate: anchorDate,
            intervalComponents: interval
        )

        query.initialResultsHandler = { _, hkStatisticsCollection, _ in
            if let hkStatisticsCollection = hkStatisticsCollection {
                completion(hkStatisticsCollection)
            }
        }

        healthStore?.execute(query)
    }

    func requestStatisticsQuery(type: HKQuantityType, predicate: NSPredicate, completion: @escaping (HKStatistics) -> Void) {
        let query = HKStatisticsQuery(
            quantityType: type,
            quantitySamplePredicate: predicate,
            options: [.cumulativeSum, .duration]) { _, statistics, _ in
            if let statistics = statistics {
                completion(statistics)
            }
        }

        healthStore?.execute(query)
    }
    
}

Booster🚀🔥

Info

Rule

Backlog

공통 모듈

구현 설명 및 기능 정리

Architecture

Architecture

회의록 & DailyScrum & 회고록

멘토링 피드백

멘토링 피드백
Clone this wiki locally