HealthKit

  1. infoPlist

    Untitled

    infoPlist쓸 때 참고하기
    <key>NSHealthShareUsageDescription</key>
    	<string>Allow my app to access health data from HealthKit.</string>
    
    <key>NSHealthUpdateUsageDescription</key>
    	<string>Allow my app to write data on Health application.</string>
    
    
  2. capabilities - HealthKit

    Untitled

    Untitled

  3. 요런게 생긴다.

    Untitled

  4. 권한 요청하기

    import Foundation
    import HealthKit
    
    // HKHelathStore: 헬스킷의 모든 데이터의 허용을 관리하는 클래스
    let healthStore = HKHealthStore()
    
    func authorizeHealthKit() {
            let read = Set([HKObjectType.quantityType(forIdentifier: .stepCount)!])
            let share = Set([HKObjectType.quantityType(forIdentifier: .stepCount)!])
            healthStore.requestAuthorization(toShare: share, read: read) {(sucess, error) in
                if(sucess) {
                    print("permission granted")
                }
            }
        }
    
  5. 하루의 걸음 수 가져오기

    → 메인뷰에 표시하기

    func getTodayTotalStepCounts() {
            
            guard let sampleType = HKCategoryType.quantityType(forIdentifier: .stepCount) else {
                return
            }
            
            let startDate = Calendar.current.startOfDay(for: Date())
            let predicate = HKQuery.predicateForSamples(withStart: startDate, end: Date(), options: .strictEndDate)
            var interval = DateComponents()
            interval.day = 1
            
            let query = HKStatisticsCollectionQuery(quantityType: sampleType, quantitySamplePredicate: predicate, options: [.cumulativeSum], anchorDate: startDate, intervalComponents: interval)
            
            query.initialResultsHandler = {
                query, result, Error in
                
                if let myresult = result {
                    myresult.enumerateStatistics(from: startDate, to: Date()) { (statistic, value) in
                        if let count = statistic.sumQuantity() {
                            let val = count.doubleValue(for: HKUnit.count())
    
    // UserDefault에 저장해서 메인뷰에 띄운다.
                            UserDefaults.standard.currentStepCount = Int(val)
    
                        }
                    }
                }
            }
            healthStore.execute(query)
        }
    

🔖 참고

How to fetch Today's Step Count using HealthKit framework iOS | Swift

HealthKit Swift getting today's steps