HealthKit

RSS for tag

Access and share health and fitness data while maintaining the user’s privacy and control using HealthKit.

HealthKit Documentation

Posts under HealthKit tag

106 Posts
Sort by:
Post not yet marked as solved
1 Replies
343 Views
The edited code still has the problem of not lining up with the health app private func fetchSleepData(for date: Date) { let sleepType = HKObjectType.categoryType(forIdentifier: .sleepAnalysis)! let endOfPeriod = date let startOfPeriod = Calendar.current.date(byAdding: .day, value: -1, to: endOfPeriod)! let predicate = HKQuery.predicateForSamples(withStart: startOfPeriod, end: endOfPeriod, options: [.strictStartDate, .strictEndDate]) let query = HKSampleQuery(sampleType: sleepType, predicate: predicate, limit: HKObjectQueryNoLimit, sortDescriptors: nil) { query, samples, error in guard let samples = samples as? [HKCategorySample], !samples.isEmpty else { DispatchQueue.main.async { self.inBedTime = 0 self.coreTime = 0 self.deepTime = 0 self.remTime = 0 self.isSleepDataAvailable = false } print("No sleep data available for date: \(date)") return } print("Fetched \(samples.count) sleep samples for date: \(date)") var inBedTime = 0.0 var asleepTime = 0.0 var deepTime = 0.0 var remTime = 0.0 for sample in samples { print("Sample value: \(sample.value)") let duration = sample.endDate.timeIntervalSince(sample.startDate) / 60 // convert to minutes switch sample.value { case HKCategoryValueSleepAnalysis.inBed.rawValue: inBedTime += duration case HKCategoryValueSleepAnalysis.asleepCore.rawValue: coreTime += duration case HKCategoryValueSleepAnalysis.asleepDeep.rawValue: deepTime += duration case HKCategoryValueSleepAnalysis.asleepREM.rawValue: remTime += duration default: break } } DispatchQueue.main.async { self.inBedTime = inBedTime self.coreTime = coreTime self.deepTime = deepTime self.remTime = remTime self.isSleepDataAvailable = true } } healthStore?.execute(query) }
Posted
by
Post not yet marked as solved
0 Replies
344 Views
I'm thinking about developing a workout tracking app. To avoid the issue of having to repeatedly download workouts, I want to persist some app model data like Apple does with their Fitness App. At a minimum, the HKWorkout class. Has anyone seen this done before? I'd hate to have reinvent the wheel. HKWorkout: HKSample: HKObject: NSObject.
Posted
by
Post not yet marked as solved
0 Replies
361 Views
Hello all, I'm trying to build a watch app for a research study built around heart rate. Currently I have built a IOS app with a companion watchOS app for a firebaseDatabase connection. There are two remaining goals of this project that include the following: While the watch app is in the background or when it's closed, is it possible for the apple watch to send a notification to the user if per say the user's heart rate goes over a custom threshold of 70bpm? If so, how should this be implemented, and can the app be consistently monitoring the heart rate to get accurate realtime notifications, or is does apple limit background updates to periodically? For this study, we want to analyze if user's actually open the watchapp because of the notifications. Is it possible to record data / track user interactions from the notifications? If so, what kind of data can be tracked and how can it be stored?
Posted
by
Post not yet marked as solved
1 Replies
522 Views
hello We are currently developing using Healthkit. Starting with xcode15, healthkit throws an error. The code causing the error is HKQuantityType(.stepCount). When I use this code An EXC_BAD_ACCESS (code=1, address=0x0) error occurs. The error is: AppDelegate It also appears when I call didFinishLaunchingWithOptions. Is the linker the problem? Or is the Swift version the problem? Or HealthKit? Cleaning and initializing DerivedData I also tried downgrading DriverKit 22.4, but the error still appears. Please tell me how to solve this problem. Test model information is as follows: -iPhone 14 Pro iOS 16.5.1
Posted
by
Post not yet marked as solved
0 Replies
357 Views
hello After updating to xcode 15.1 while using xcode 14.3, I keep getting EXC_BAD_ACCESS (code=1, address=0x0) in HealthKit's HKQuantityType(.stepCount). We also created and tested HKQuantityType(.stepCount) in the appDelegate class. But it comes out the same as above. I think there has been a change in library building and linking starting from xcode15. Please guide me what to do about this problem. The test model is iphone 14 pro It's 16.5.1.
Posted
by
Post not yet marked as solved
0 Replies
434 Views
Errors: ''Invalid info.plist key. The key 'NSHealthShareUsageDescription'' ''Invalid info.plist key. The key 'NSHealthUpdateUsageDescription'' The app works fine when I just run it on hardware without deployment, but as soon as I try to distribute it, this shows up. The keys above are both defined and described in my App and extensions lists, so what's wrong?
Posted
by
Post not yet marked as solved
0 Replies
363 Views
I have the same issues, when i use HKStatisticsCollectionQuery query user step count, there's a big difference in the number of steps I'm query before and after a minute's interval. 2023-12-17 15:45:41 steps=529 2023-12-17 15:46:52 steps=5817 2023-12-19 19:43:59 steps=2680 2023-12-19 19:44:31 steps=5554 What is causing this issue? I would like some assistance, please.
Posted
by
Post not yet marked as solved
0 Replies
411 Views
With the recent iPad OS 17 release, Apple added the Health app for the first time. Looking at it, it seems pretty similar to the phone version as the Health app only shows 'historical' health data. My question is this: We are developing an iPad based fitness app. Is there any way of getting real-time health data from the Apple Watch directly to an iPad app? (basically, we just need heart rate). Or, do we have create some sort of workflow through the Phone like Watch -> iPhone running our app -> our servers -> iPad running our app ..to get that real-time data? We really just want Watch -> iPad running our app. I'm afraid I already know the answer but just thought I'd check in case I'm missing something in iOS 17. Thanks!
Posted
by
Post not yet marked as solved
1 Replies
418 Views
Our app uses HKWorkoutSession after some actions, to keep app on high priority in background and to keep Apple Watch returns to our app when the watch is waked up. We don't collect or register any activity record. But for some reasons, some users reviewed our app saying that when they're using our app, the Workout app on Apple Watch seems to be affected, ex: Move and exercises is recorded as an abnormal/impossible value... . Is this possible? I don't see any document mention this side effect?
Posted
by
Post not yet marked as solved
0 Replies
391 Views
Hello, it is discussed here https://developer.apple.com/videos/play/wwdc2023/10016/ (12:16) regarding WorkoutComposition, but unfortunately, I cannot find this class or structure in the documentation. Has this concept been removed?
Posted
by
Post not yet marked as solved
1 Replies
437 Views
I have created a new project and I have added HomeKit capability but the two control box for Clinical Health Records and Background Delivery can not be switched on. are there any suggestion? thanks a lot valerio
Posted
by
Post not yet marked as solved
0 Replies
346 Views
After some years our app has been writing some data to HealthKit we decided to remove this functionality from the app. Permissions were removed from requestAuthorization(toShare:read:completion:) method. For new users everything works fine, but for users who were already asked for writing permission in Settings toggles for permissions are still on. Is it any way to update toggles list in Settings for actual state of permissions? Thanks in advance.
Posted
by
Post not yet marked as solved
2 Replies
404 Views
Hi, Our app has an HKObserverQuery and calls enableBackgroundDelivery(...) While running on an iPhone the background wakeup happens. While running on an iPad, it doesn't. The app can successfully query for data while in the foreground on an iPad. Is background delivery expected to work on iPad?
Posted
by
Post not yet marked as solved
0 Replies
355 Views
Even if you have granted read permission for specific health data items (such as walking, weight, etc.), calling the function below will return the permission as 'sharingDenied'. How can I obtain 'sharingAuthorized'? let stepType = HKObjectType.quantityType(forIdentifier: .stepCount)! let authorizationStatus = HKHealthStore().authorizationStatus(for: stepType) //authorizationStatus => sharingDenied
Posted
by
Post not yet marked as solved
0 Replies
405 Views
https://idmsa.apple.com/IDMSWebAuth/signin?path=%2F%2Fforums%2Fpost%2Fquestion%3Flogin%3Dtrue&language=US-EN&instanceId=EN&appIdKey=25138a77e3499638936f018102a53961c923f72b517d4a4d6aee9f09529baca9&rv=4 I've built and tested the code obtained from this site, but although the session starts, pausing or stopping it doesn't seem to work properly. Does anyone know what might be causing this issue? I'm using the latest versions of iOS and watchOS, and my Xcode is version 15.0.1. The main code is as follows, and the session does not start properly in startWorkout. import Foundation import os import HealthKit @MainActor class WorkoutManager: NSObject, ObservableObject { struct SessionSateChange { let newState: HKWorkoutSessionState let date: Date } @Published var sessionState: HKWorkoutSessionState = .notStarted @Published var heartRate: Double = 0 @Published var activeEnergy: Double = 0 @Published var speed: Double = 0 @Published var power: Double = 0 @Published var cadence: Double = 0 @Published var distance: Double = 0 @Published var water: Double = 0 @Published var elapsedTimeInterval: TimeInterval = 0 @Published var workout: HKWorkout? let typesToShare: Set = [HKQuantityType.workoutType(), HKQuantityType(.dietaryWater)] let typesToRead: Set = [ HKQuantityType(.heartRate), HKQuantityType(.activeEnergyBurned), HKQuantityType(.distanceWalkingRunning), HKQuantityType(.cyclingSpeed), HKQuantityType(.cyclingPower), HKQuantityType(.cyclingCadence), HKQuantityType(.distanceCycling), HKQuantityType(.dietaryWater), HKQuantityType.workoutType(), HKObjectType.activitySummaryType() ] let healthStore = HKHealthStore() var session: HKWorkoutSession? #if os(watchOS) var builder: HKLiveWorkoutBuilder? #else var contextDate: Date? #endif let asynStreamTuple = AsyncStream.makeStream(of: SessionSateChange.self, bufferingPolicy: .bufferingNewest(1)) static let shared = WorkoutManager() private override init() { super.init() Task { for await value in asynStreamTuple.stream { await consumeSessionStateChange(value) } } } /** Consume the session state change from the async stream to update sessionState and finish the workout. */ private func consumeSessionStateChange(_ change: SessionSateChange) async { sessionState = change.newState /** Wait for the session to transition states before ending the builder. */ #if os(watchOS) /** Send the elapsed time to the iOS side. */ let elapsedTimeInterval = session?.associatedWorkoutBuilder().elapsedTime(at: change.date) ?? 0 let elapsedTime = WorkoutElapsedTime(timeInterval: elapsedTimeInterval, date: change.date) if let elapsedTimeData = try? JSONEncoder().encode(elapsedTime) { await sendData(elapsedTimeData) } guard change.newState == .stopped, let builder else { return } let finishedWorkout: HKWorkout? do { try await builder.endCollection(at: change.date) finishedWorkout = try await builder.finishWorkout() session?.end() } catch { Logger.shared.log("Failed to end workout: \(error))") return } workout = finishedWorkout #endif } } // MARK: - Workout session management // extension WorkoutManager { func resetWorkout() { #if os(watchOS) builder = nil #endif workout = nil session = nil activeEnergy = 0 heartRate = 0 distance = 0 water = 0 power = 0 cadence = 0 speed = 0 sessionState = .notStarted } func sendData(_ data: Data) async { do { try await session?.sendToRemoteWorkoutSession(data: data) } catch { Logger.shared.log("Failed to send data: \(error)") } } } extension WorkoutManager: HKWorkoutSessionDelegate { nonisolated func workoutSession(_ workoutSession: HKWorkoutSession, didChangeTo toState: HKWorkoutSessionState, from fromState: HKWorkoutSessionState, date: Date) { Logger.shared.log("Session state changed from \(fromState.rawValue) to \(toState.rawValue)") let sessionSateChange = SessionSateChange(newState: toState, date: date) asynStreamTuple.continuation.yield(sessionSateChange) } nonisolated func workoutSession(_ workoutSession: HKWorkoutSession, didFailWithError error: Error) { Logger.shared.log("\(#function): \(error)") } nonisolated func workoutSession(_ workoutSession: HKWorkoutSession, didDisconnectFromRemoteDeviceWithError error: Error?) { Logger.shared.log("\(#function): \(error)") } nonisolated func workoutSession(_ workoutSession: HKWorkoutSession, didReceiveDataFromRemoteWorkoutSession data: [Data]) { Logger.shared.log("\(#function): \(data.debugDescription)") Task { @MainActor in do { for anElement in data { try handleReceivedData(anElement) } } catch { Logger.shared.log("Failed to handle received data: \(error))") } } } } private func startWorkout() { Task { do { let configuration = HKWorkoutConfiguration() configuration.activityType = .cycling configuration.locationType = .outdoor try await workoutManager.startWorkout(workoutConfiguration: configuration) } catch { Logger.shared.log("Failed to start workout \(error))") } } }
Posted
by
Post not yet marked as solved
0 Replies
379 Views
With iOS 17 creation of HKWorkout is deprecated via its init functions and the recommendation is to use HKWorkoutBuilder. If you try to init HKWorkout like you would pre iOS 17 you get this warning of deprecation: The problem is that I am creating this HKWorkout object inside unit tests in order to test a service that works with such objects. And HKWorkoutBuilder requires a HKHealthStore which itself requires to be authenticated to be able to create HKWorkoutActivity instances, like it would be when an app is running. But since the unit tests cannot accept the request on the HKHealthStore I am not sure if using HKWorkoutBuilder inside unit tests is possible. I've also tried to inherit HKHealthStore and override all of its methods, but still, store requires authorization. Any ideas on how to proceed with creating HKWorkout for unit test purposes?
Posted
by
Post not yet marked as solved
0 Replies
276 Views
Hello developers, I hope you're all doing well. I've encountered an issue that I'm struggling to resolve, and I'd greatly appreciate any insights or assistance you can offer. Issue Summary: In my watchOS app, I'm utilizing the HKWorkoutSessionDelegate protocol and the workoutSession(_:didFailWithError:) method. While everything works smoothly on watchOS 9.*, I'm facing a problematic inconsistency on watchOS 10.0 and higher. Steps to Reproduce: Create a new watchOS project with a deployment target of watchOS 10.0 or higher. Implement the HKWorkoutSessionDelegate protocol and the workoutSession(_:didFailWithError:) method. Attempt to start a workout session. Expected Behavior: I expect the workout session to commence without any issues, and the delegate method to gracefully handle any errors, without displaying an error message. Actual Behavior: Unfortunately, on watchOS 10.0 and higher, my attempts to initiate a workout session result in an error message: "Cannot start workout session while process is in the background." Version/Build: Affected watchOS versions: 10.0 and higher Non-affected watchOS versions: 9.* Reproducibility: I've confirmed that this issue is reproducible across different projects and on different simulators running watchOS 10.0 and higher. Additional Information: This inconsistency seems to be specific to watchOS versions 10.0 and higher and doesn't occur on watchOS 9.*. It's causing confusion and hampering my development process, and the error message isn't as informative as I'd like. Workaround: I've been unable to identify a workaround for this issue so far. If any of you have insights, solutions, or suggestions, I'd be grateful for your input. Please feel free to share your experiences and thoughts on this matter. Your help is greatly appreciated! Thank you for your time and assistance. Best regards, Leonid
Posted
by
Post marked as solved
2 Replies
372 Views
iPadOS 17 brings HealthKit to the iPad. So I've updated my HealthKit-using app to also run on iPadOS. I can debug it from Xcode on iPad simulators and my iPad, but when I upload a build to AppStoreConnect from Xcode and try to install it on my iPad from TestFlight, the install-button is missing and instead there is a label saying "incompatible hardware". The app has no other required device capabilities besides healthkit. It was also updated to at least require iOS/iPadOS 17. I can install it on my iPhone but not on the iPad. I also noticed that in this list https://developer.apple.com/support/required-device-capabilities/#ipad-devices no iPad model has the healthkit device capability. Why? Is there some way to find out why exactly TestFlight thinks the iPad is incompatible hardware? Thanks in advance to anyone who can enlighten me here.
Posted
by
Post not yet marked as solved
2 Replies
450 Views
In the wwdc2023-10023 session, we go over how the Apple Watch can be used as a primary workout session manager and the iPhone as the mirrored one. How is it possible to create a workout session on the iPhone and optionally mirror it to the Apple Watch to collect heart rate data? In iOS 17, I still cannot instantiate a HKWorkoutSession, I'm assuming it says it's available because we can have an instance of it as a mirrored copy from the Apple Watch. I find it odd that the iPhone cannot manage the primary session. I hope I'm missing something.
Posted
by
Post not yet marked as solved
0 Replies
397 Views
Hi, with iOS 17 creation of HKWorkout is deprecated via its init functions and the recommendation is to use HKWorkoutBuilder: The problem is that I am creating this HKWorkout object inside unit tests in order to test a service that works with such objects. And HKWorkoutBuilder requires a HKHealthStore which itself requires to be authenticated to be able to create HKWorkoutActivity instances, like it would be when an app is running. But since the unit tests cannot accept the request on the HKHealthStore I am not sure if using HKWorkoutBuilder inside unit tests is possible. Any ideas on how to proceed with creating HKWorkout for unit test purposes?
Posted
by