top of page

SwiftUI: Alcohol Content Check: HealthKit, and CareKit Walk into a Bar 🍻 iOS

Updated: Mar 25, 2023

Learn how to create a fun and easy SwiftUI app that utilizes HealthKit and CareKit to monitor users’ blood alcohol content (BAC)


Welcome, dear beginners and fellow programmers, to a journey where we’ll be brewing up a delightful concoction of SwiftUI, HealthKit, and CareKit! In this article, we’ll create an app to measure users’ blood alcohol content (BAC). And don’t worry, our path will be paved with light, funny jokes to keep you engaged and entertained. Cheers! 🥂


Part 1: Prepping the Ingredients 🍇

Before we start concocting our app, make sure you have the following:

  1. A Mac running macOS Monterey or later

  2. Xcode 13 or later

  3. An Apple Developer account (to access HealthKit and CareKit)

  4. A taste for fun and an appetite for learning! 🍽️

Step 1: Create a New SwiftUI Project


Fire up Xcode, and create a new project using the “App” template under “Multiplatform” or “iOS.” Name your project “BACMonitor” and ensure “Interface” is set to “SwiftUI” and “Life Cycle” to “SwiftUI App.”


Step 2: Import HealthKit and CareKit


In your project’s “Signing & Capabilities” tab, click on “+ Capability” and add “HealthKit” and “CareKit” to your app. You’ll need to sign in with your Apple Developer account to access these frameworks.

Now that we’re all set, let’s dive into the world of SwiftUI, HealthKit, and CareKit!


Part 2: Mixing SwiftUI, HealthKit, and CareKit 🍹


To create our BAC monitoring app, we’ll develop a simple SwiftUI interface that displays users’ blood alcohol content and allows them to enter new BAC data.


Step 1: The SwiftUI Interface


First, let’s create a simple SwiftUI interface with a TextField to input BAC data and a Text view to display the latest BAC value.

import SwiftUI
import HealthKit

struct ContentView: View {
    @State private var bacInput: String = ""
    @State private var latestBAC: Double = 0.0
    @ObservedObject private var healthStore = HealthStore()

    var body: some View {
        VStack {
            TextField("Enter your BAC", text: $bacInput)
                .textFieldStyle(RoundedBorderTextFieldStyle())
                .keyboardType(.decimalPad)
                .padding()

            Button("Submit BAC") {
                if let bacValue = Double(bacInput) {
                    healthStore.addBACData(bacValue: bacValue)
                    bacInput = ""
                }
            }
            .padding()

            Text("Latest BAC: \(latestBAC, specifier: "%.3f")")
                .padding()
        }
        .onAppear {
            healthStore.getLatestBAC { result in
                latestBAC = result
            }
        }
    }
}

Step 2: Setting Up HealthKit


Now, let’s create a HealthStore class to manage our interactions with HealthKit.

import HealthKit

class HealthStore: ObservableObject {
    private let healthStore = HKHealthStore()

    // ... more code to come
}

First, request authorization for BAC data:

init() {
    requestAuthorization()
}

private func requestAuthorization() {
    let typesToShare: Set = [HKObjectType.quantityType(forIdentifier: .bloodAlcoholContent)!]
    let typesToRead: Set = [HKObjectType.quantityType(forIdentifier: .bloodAlcoholContent)!]

    healthStore.requestAuthorization(toShare: typesToShare, read: typesToRead) { success, error in
        if let error = error {
            print("Error requesting authorization: \(error.localizedDescription)")
        }
    }
}

Next, create a function to save BAC data to HealthKit:

func addBACData(bacValue: Double) {
    guard let bacType = HKObjectType.quantityType(forIdentifier: .bloodAlcoholContent) else { return }

    let bacQuantity = HKQuantity(unit: HKUnit.percent(), doubleValue: bacValue)
    let bacSample = HKQuantitySample(type: bacType, quantity: bacQuantity, start: Date(), end: Date())

    healthStore.save(bacSample) { success, error in
        if let error = error {
            print("Error saving BAC data: \(error.localizedDescription)")
        }
    }
}

Lastly, create a function to fetch the latest BAC value:

func getLatestBAC(completion: @escaping (Double) -> Void) {
    guard let bacType = HKObjectType.quantityType(forIdentifier: .bloodAlcoholContent) else { return }

    let sortDescriptor = NSSortDescriptor(key: HKSampleSortIdentifierStartDate, ascending: false)
    let query = HKSampleQuery(sampleType: bacType, predicate: nil, limit: 1, sortDescriptors: [sortDescriptor]) { _, samples, error in
        if let error = error {
            print("Error fetching BAC data: \(error.localizedDescription)")
            completion(0.0)
        } else if let sample = samples?.first as? HKQuantitySample {
            let bacValue = sample.quantity.doubleValue(for: HKUnit.percent())
            completion(bacValue)
        } else {
            completion(0.0)
        }
    }

    healthStore.execute(query)
}


Part 3: The Last Sip — Conclusion 🍺


Cheers, fellow programmers! You’ve successfully crafted a fun and easy SwiftUI app that leverages HealthKit and CareKit to monitor users’ blood alcohol content. As you venture further into the world of iOS development, remember that this article is just a small sip of the vast ocean of possibilities. Keep exploring, and don’t be afraid to mix and match frameworks to create a delightful cocktail of apps! 🍹


“When life gives you SwiftUI, HealthKit, and CareKit, make an app and monitor your BAC responsibly.” — Probably some wise developer at Happy Hour.




2 views0 comments
bottom of page