Hey y’all,
I’m building a health app where I can’t get the options to show up, it is a blank screen like this instead:
I also tried it on my phone, but the results were the same. What can I do? my source code is below:
My HealthView.swift file:
import SwiftUI
import HealthKit
struct Health: View {
private var respository = HKRespository()
var body: some View {
NavigationView {
ScrollView(.vertical, showsIndicators: false) {
List {
ForEach(Activity.allActivities()) { activity in
Text(activity.title)
}
}
.onAppear {
respository.requestAuthorization { success in
print("Auth success? \(success)")
}
}
}
.navigationBarTitle("Health")
.background(Color.black.opacity(0.03).ignoresSafeArea())
.navigationViewStyle(StackNavigationViewStyle())
}
}
}
struct Health_Previews: PreviewProvider {
static var previews: some View {
Health()
}
}
struct HealthTile: View {
var title: String
var icon: String
var body: some View {
HStack {
Image(systemName: icon)
.font(.largeTitle)
Spacer()
Text(title)
.font(.largeTitle)
}
.frame(width: 200, height: 100)
.cornerRadius(20)
}
}
My HKRespository.swift file:
import Foundation
import HealthKit
final class HKRespository {
var store: HKHealthStore?
let allTypes = Set([
HKObjectType.quantityType(forIdentifier: .activeEnergyBurned)!,
HKObjectType.quantityType(forIdentifier: .appleExerciseTime)!,
HKObjectType.quantityType(forIdentifier: .appleStandTime)!,
HKObjectType.quantityType(forIdentifier: .distanceWalkingRunning)!,
HKObjectType.quantityType(forIdentifier: .stepCount)!,
])
var query: HKStatisticsCollectionQuery?
init() {
store = HKHealthStore()
}
func requestAuthorization(completion: @escaping (Bool) -> Void) {
guard let store = store else {
return
}
store.requestAuthorization(toShare: [], read: allTypes) { success, error in
completion(success)
}
}
func requestHealthStat(by category: String, completion: @escaping ([HealthStat]) -> Void) {
guard let store = store, let type = HKObjectType.quantityType(forIdentifier: typeByCategory(category: category)) else {
return
}
let startDate = Calendar.current.date(byAdding: .day, value: -7, to: Date()) ?? Date()
let endDate = Date()
let anchorDate = Date.firstDayOfWeek()
let dailyComponents = DateComponents(day: 1)
var healthStats = [HealthStat]()
let predicate = HKQuery.predicateForSamples(withStart: startDate, end: endDate, options: .strictStartDate)
query = HKStatisticsCollectionQuery(quantityType: type, quantitySamplePredicate: predicate, options: .cumulativeSum, anchorDate: anchorDate, intervalComponents: dailyComponents)
query?.initialResultsHandler = { query, statistics, error in
statistics?.enumerateStatistics(from: startDate, to: endDate, with: { stats, _ in
let stat = HealthStat(stat: stats.sumQuantity(), date: stats.startDate)
healthStats.append(stat)
})
completion(healthStats)
}
guard let query = query else {
return
}
store.execute(query)
}
private func typeByCategory(category: String) -> HKQuantityTypeIdentifier {
switch category {
case "activeEnergyBurned":
return .activeEnergyBurned
case "appleExerciseTime":
return .appleExerciseTime
case "appleStandTime":
return .appleStandTime
case "distanceWalkingRunning":
return .distanceWalkingRunning
case "stepCount":
return .stepCount
default:
return .stepCount
}
}
}
extension Date {
static func firstDayOfWeek() -> Date {
return Calendar(identifier: .iso8601).date(from: Calendar(identifier: .iso8601).dateComponents([.yearForWeekOfYear, .weekOfYear], from: Date())) ?? Date()
}
}
And my Activities.swift file:
import Foundation
import HealthKit
struct Activity: Identifiable {
var id: String
var title: String
var image: String
static func allActivities()-> [Activity] {
return [
Activity(id: "activeEnergyBurned", title: "Calories Burned", image: "bolt.circle.fill"),
Activity(id: "appleExerciseTime", title: "Exercise Time", image: "lungs.fill"),
Activity(id: "appleStandTime", title: "Stand Time", image: "figure.stand"),
Activity(id: "distanceWalkingRunning", title: "Distance Walking/Running", image: "figure.wave.circle.fill"),
Activity(id: "stepCount", title: "Steps", image: "figure.walk.diamond.fill"),
]
}
}
struct HealthStat: Identifiable {
let id = UUID()
let stat: HKQuantity?
let date: Date
}
Any help on this would be appreciated, thanks!