How do I add my hospital to the list of hospitals available on the Health Records on iPhone application?
                    
                  
                Health & Fitness
RSS for tagExplore the technical aspects of health and fitness features, including sensor data acquisition, health data processing, and integration with the HealthKit framework.
  
    
    Selecting any option will automatically load the page
  
  
  
  
    
  
  
            Post
Replies
Boosts
Views
Activity
                    
                      Hi!
I am using the HKAnchoredObjectQuery to first get a snapshot of the initial results, and then trigger an updateHandler.
I need to handle the initial results and the updates separately, which is why I implemented two completions.
When I test the code, it works for a while. New and deleted samples trigger the updateHandler. However, after a while there appears an error:
[connection] nw_read_request_report [C2] Receive failed with error "Software caused connection abort"
Followingly, the updateHandler will stop getting triggered when I add updates in Apple health. Anyone have experience with this?
func getMostRecentSample(for sampleType: HKSampleType, 
anchorKey: String, 
completion: @escaping (HKQuantitySample?, Error?) -> Swift.Void, 
updateHandler: @escaping (HKQuantitySample, Error?) -> Swift.Void) {
    // If it is the first initialization, anchor is passed as nil
    var anchor: HKQueryAnchor? = nil
    // Check for previous saved anchor in userdefaults
    if UserDefaults.standard.object(forKey: anchorKey) != nil {
      let data = UserDefaults.standard.object(forKey: anchorKey) as! Data
      do {
        guard let newAnchor = try NSKeyedUnarchiver.unarchivedObject(ofClass: HKQueryAnchor.self, from: data) else {
          print("Could not parse anchor to HKQueryAnchor type")
          return
        }
        anchor = newAnchor
      } catch {
        print("Error retreiving anchor from UserDefaults")
      }
    }
    let query = HKAnchoredObjectQuery(type: sampleType,
                     predicate: nil,
                     anchor: anchor,
                     limit: HKObjectQueryNoLimit
                      ) { (query, samplesOrNil, _, newAnchor, errorOrNil) in
      guard let samples = samplesOrNil as? [HKQuantitySample] else {
        fatalError("*** An error occurred during the initial query: \(errorOrNil!.localizedDescription) ***")
      }
      if let anchor = newAnchor {
        do {
          let data = try NSKeyedArchiver.archivedData(withRootObject: anchor as Any, requiringSecureCoding: false)
          UserDefaults.standard.set(data, forKey: anchorKey)
        } catch {
          print("Error retreiving anchor from UserDefaults")
        }
      }
      completion(samples.last, nil)
    }
     
    // Setting up long-running query
    query.updateHandler = { (query, samplesOrNil, _, newAnchor, errorOrNil) in
      guard let samples = samplesOrNil as? [HKQuantitySample] else {
        fatalError("*** An error occurred during an update: \(errorOrNil!.localizedDescription) ***")
      }
      if let anchor = newAnchor {
        do {
          let data = try NSKeyedArchiver.archivedData(withRootObject: anchor as Any, requiringSecureCoding: false)
          UserDefaults.standard.set(data, forKey: anchorKey)
        } catch {
          print("Error retreiving anchor from UserDefaults")
        }
      }
      if let sample = samples.last {
        updateHandler(sample, nil)
      }
    }
    self.healthStore.execute(query)
  }
                    
                  
                
                    
                      I am creating a watchOS app with XCode, and am experiencing an issue where workouts do not start on watchOS versions 9.6.3 and later.
・App specifications
Start workout when app starts
code (swift)
workout?.startActivity(with: Date())
·phenomenon
In watchOS version 9.6.3 or later, after the Apple Watch runs out of battery or is turned off.
When you turn on your Apple Watch and start using it, even if you start a workout (startActivity),The status may not change to running and the workout may not work.
*Workout always worked on watchOS versions earlier than version 9.6.3.
*The workout will work if you close the app and start the app again.
If anyone has any information, please provide it.
                    
                  
                
              
                
              
              
                
                Topic:
                  
	
		App & System Services
  	
                
                
                SubTopic:
                  
                    
	
		Health & Fitness
		
  	
                  
                
              
              
              
  
  
    
    
  
  
              
                
                
              
            
          
                    
                      We are seeing an issue where sending data using the asynchronous method HKWorkoutSession.sendToRemoteWorkoutSession(data: Data) will never return in some cases (no success nor failure).
This issue is happening for roughly 5% of Workouts started and will stay broken for the whole workout. The other 95% of the workouts, the connection works flawlessly. This happens on both watchOS 10 and 11, and with phones running iOS 17 or 18. The issue is quite random and not reproducible.
Our app has thousands of workouts a day that use the workout session workout data send, with constant messages being send every few seconds.
In some of those 5% cases the "sendToRemoteWorkoutSession" will throw way later, like 30+ minutes later, if the watch app is awake long enough to capture a log of a failure.
Our code uses the same flow as in the sample project:
https://developer.apple.com/documentation/healthkit/workouts_and_activity_rings/building_a_multidevice_workout_app
Here is some sample code, which is pretty simple.
Setup code:
let workoutSession = try HKWorkoutSession(healthStore: healthStore, configuration: configuration)
workoutSession.delegate = self
activeWorkoutSession?.startMirroringToCompanionDevice { success, error in
    print("Mirroring started on companion device: \(success), error: \(error)")
}
workoutSession?.prepare()
then later we send data using the workout session:
do {
    print("Will send data")
    try await workoutSession.sendToRemoteWorkoutSession(data: data)
    print("Successfully sent data") // This nor the error may be called after waiting extensive amounts of time
} catch {
    print("Failed to send data, error: \(error)")  // This nor the success may be called after waiting extensive amounts of time
}
So far, the only fix is to restart the phone and watch at the same time, which is not a great user experience.
Is anyone else seeing this issue? or know how to fix this issue?
                    
                  
                
              
                
              
              
                
                Topic:
                  
	
		App & System Services
  	
                
                
                SubTopic:
                  
                    
	
		Health & Fitness
		
  	
                  
                
              
              
                Tags:
              
              
  
  
    
      
      
      
        
          
            Watch Connectivity
          
        
        
      
      
    
      
      
      
        
          
            Health and Fitness
          
        
        
      
      
    
      
      
      
        
          
            watchOS
          
        
        
      
      
    
      
      
      
        
          
            WorkoutKit
          
        
        
      
      
    
  
  
              
                
                
              
            
          
                    
                      When we upload workout data to HealthKit the route information with the workout detailed data is incomplete: just a few dots.
When we select "Show all workout routes" the route data for the same workout shows correctly.
We use the HKWorkoutBuilder to store the workout data, and add the location data with the HKWorkoutRouteBuilder to the workout with
Is this an Apple Health issue, or do we have to change something in the way we store the location data to the workout?
                    
                  
                
              
                
              
              
                
                Topic:
                  
	
		App & System Services
  	
                
                
                SubTopic:
                  
                    
	
		Health & Fitness
		
  	
                  
                
              
              
              
  
  
    
    
  
  
              
                
                
              
            
          
                    
                      My Apple Watch after the beta update is not syncing the activities sometimes with Apple Health.
I just completed a 2.5 km walk, and it showed on Apple Health, yes, but it did not affect my daily goals. This is not the first time this has happened; this is just one of the examples that I'm sharing, other than what has been some problems that I am seeing after the beta update.
Additionally, the camera remote app is not working correctly as I cannot see anything on the watch screen like I used to.
                    
                  
                
                    
                      For a given date, there are discrepancies between the step counts obtained from HealthKit and those displayed in the Health app. Is it possible for such discrepancies to occur even if step counts are not manually entered and multiple devices are not being used?
                    
                  
                
                    
                      Hi guys,
In WWDC23 session 10016: Build custom workouts with WorkoutKit , the presenters mentioned that a Workout Plan can be exported to a JSON or binary file, and also showed a code snip:
let binaryRepresentation = try myCyclingWorkout.dataRepresentation(in: .compactBinary)
However in the current SDK, the property dataRepresentation can not be exported with a specific format, the base64EncodedString() result is unreadable.
Does anyone know how to export it as a JSON string now? Thanks very much.
                    
                  
                
                    
                      I started with the custom workout example from Apple. I was able to load the apps from my mac (xcode) to my iphone. I can run the apps on my iphone. I completed the authorization and reviewed the workout. I then uploaded the workout to the watch and it appeared to work. It never showed up on the watch. I tried restarting the watch and iPhone. I have. a second watch and I tried that. Nothing helped. IPhone 14 with ios 18.2. Watch is Series 6 with watch OS 11.2. I also tried it with the watch on the charger but no change. Workout Kit seems like a good idea, but not if you cannot get it on your watch. It seems very few people are using it as there is little info online.
                    
                  
                
              
                
              
              
                
                Topic:
                  
	
		App & System Services
  	
                
                
                SubTopic:
                  
                    
	
		Health & Fitness
		
  	
                  
                
              
              
              
  
  
    
    
  
  
              
                
                
              
            
          
                    
                      I'm encountering an issue with HealthKit permissions and would appreciate some guidance:
In my app's previous version, I granted write permissions for HKObjectType.workoutType() via the WatchKitExtension. Now, in the upcoming version, I'm trying to request read permissions for both HKObjectType.workoutType() and HKSeriesType.workoutRoute() via the iOS app.
However, after granting access:
The read permissions for Workout and Workout Route don't show up under Settings -> Health -> Data and Access -> [My App].
The Workout Route permission status remains notDetermined, even though I selected "Allow" when prompted.
Interestingly, if I request the same permissions via the WatchKitExtension, everything works as expected, and the issue doesn't occur.
Has anyone experienced a similar issue or have insights into why this might be happening? Could it be related to requesting permissions from the iOS app instead of the WatchKitExtension?
                    
                  
                
                    
                      good morning every one, hopefully this is the right place where to speak.
I am not a developer and I am not familiar with and programming.
I am a simple apple user and happend to me that my diving watch died few weeks ago. Since then I am using Apple Watch Ultra to free dive and spare fishing.
Honestly we few small modifications this watch can take the lead over Garmin and Suunto that at the moment are the two best watch on the market for this specific area.
will it be possible to give some feedbacks and develop the app?
many Thanks
Mickey
                    
                  
                
              
                
              
              
                
                Topic:
                  
	
		App & System Services
  	
                
                
                SubTopic:
                  
                    
	
		Health & Fitness
		
  	
                  
                
              
              
              
  
  
    
    
  
  
              
                
                
              
            
          
                    
                      As a user, there are times when I don't wear my sleep tracker to bed, but I nonetheless want to record my sleep times.
Apple Health supports this with the "Add Data" feature, but it's not possible to provide a time zone in the form.
Then as a developer, user-added sleep samples are missing time zone information.
I would expect that the time zone is requested within the Add Data form.
Without this information provided at input time, downstream applications are forced to infer the time zone ourselves, leading to potentially buggy or unintuitive behavior.
                    
                  
                
                    
                      We have working code to fetch step data from HealthKit after requesting the necessary permissions. However, we’ve encountered an issue specific to one device, the iPhone 16 Pro Max. When querying the data, we do not receive a response, and the code enters an infinite loading state without completing the request.
The user who is facing this issue has tried logging in on another device, and it works fine. On the problematic device (iPhone 16 Pro Max), the request does not complete.
For reference, I’ve included the code below. Resolving this issue is crucial, so we would appreciate any guidance on what steps we can take to troubleshoot or resolve the problem on this specific device.
Please note that the device has granted permission to access HealthKit data.
static let healthStore = HKHealthStore()
static func limitReadFromHealthKitBetweenDates(fromDate: Date, toDate: Date = Date(), completion: @escaping ([HKStatistics]) -> Void) {
    guard let stepsQuantityType = HKQuantityType.quantityType(forIdentifier: .stepCount) else { return }
    let ignoreUserEntered = HKQuery.predicateForObjects(withMetadataKey: HKMetadataKeyWasUserEntered, operatorType: .notEqualTo, value: true)
    let now = toDate
    var interval = DateComponents()
    interval.day = 1
    var calendar = Calendar.current
    calendar.locale = Locale(identifier: "en_US_POSIX")
    var anchorComponents = calendar.dateComponents([.day, .month, .year], from: now)
    anchorComponents.hour = 0
    let anchorDate = calendar.date(from: anchorComponents) ?? Date()
    let query = HKStatisticsCollectionQuery(quantityType: stepsQuantityType,
                                            quantitySamplePredicate: ignoreUserEntered,
                                            options: [.cumulativeSum],
                                            anchorDate: anchorDate,
                                            intervalComponents: interval)
    query.initialResultsHandler = { _, results, error in
        guard let results = results else {
            print("Error returned from resultHandler: \(String(describing: error?.localizedDescription))")
            return
        }
        
        print(results)
        
        var statisticsArray: [HKStatistics] = []
        results.enumerateStatistics(from: fromDate, to: now) { statistics, _ in
            statisticsArray.append(statistics)
            
            if statistics.endDate.getddmmyyyyslashGMT == now.getddmmyyyyslashGMT {
                completion(statisticsArray)
            }
        }
    }
    healthStore.execute(query)
}
Please note that the code works on all devices except the problematic one. Could you please guide me on the next steps to resolve this issue?
                    
                  
                
              
                
              
              
                
                Topic:
                  
	
		App & System Services
  	
                
                
                SubTopic:
                  
                    
	
		Health & Fitness
		
  	
                  
                
              
              
                Tags:
              
              
  
  
    
      
      
      
        
          
            iOS
          
        
        
      
      
    
      
      
      
        
          
            iPhone
          
        
        
      
      
    
      
      
      
        
          
            Health and Fitness
          
        
        
      
      
    
      
      
      
        
          
            HealthKit
          
        
        
      
      
    
  
  
              
                
                
              
            
          
                    
                      I have a workout app which I am testing on device currently via TestFlight.
The generated workout (tennis and indoor) shows in the fitness app with correct HR and duration.
However, when I go to my Strava app, it does not show in the list of workouts for importing.  (note, activities tracked using the regular tennis mode on the Apple Watch show fine)
I have also concurrently reached out to Strava support to see if there's anything they can offer support for.
However, does anybody here have any knowledge/experience of the requirement?  Or whether this is a limitation of an application deployed via TestFlight?
I have a terrible feeling I am chasing ghosts, and it may be a TestFlight limitation for exporting workouts?
Thanks
                    
                  
                
              
                
              
              
                
                Topic:
                  
	
		App & System Services
  	
                
                
                SubTopic:
                  
                    
	
		Health & Fitness
		
  	
                  
                
              
              
                Tags:
              
              
  
  
    
      
      
      
        
          
            Health and Fitness
          
        
        
      
      
    
      
      
      
        
          
            HealthKit
          
        
        
      
      
    
      
      
      
        
          
            TestFlight
          
        
        
      
      
    
  
  
              
                
                
              
            
          
                    
                      I want to use the Apple Healthkit data to recommend personalised insurance. Is this allowed? As I have read in the documentation that the Apple Healthkit data can only be used for fitness and health purposes. Anyone knows what is meant / scope of "fitness and health purposes"? Will personalised insurance as per health data be allowed under this category?
                    
                  
                
                    
                      Hello,
My app syncs workout data from a third-party device and records workouts with HealthKit as follows:
let builder = HKWorkoutBuilder(healthStore: healthStore, configuration: hkConf, device: hkDevice)
try await builder.beginCollection(at: startDate)
try await builder.addSamples(samples)
try await builder.endCollection(at: endDate)
let workout = try await builder.finishWorkout()
let workoutRouteBuilder = HKWorkoutRouteBuilder(healthStore: healthStore, device: hkDevice)
try await workoutRouteBuilder.insertRouteData(filteredLocations)
try await workoutRouteBuilder.finishRoute(with: workout, metadata: nil)
However, I’m encountering two issues:
The workouts appear in Apple Fitness but do not contribute to the activity rings.
The workout includes a route (visible in the raw workout data in Apple Health) but does not display on Apple Fitness.
Is there any way to fix this? I’d appreciate any suggestions you might have.
__
                    
                  
                
                    
                      I am using a new Apple Watch Ultra 2 (MX5R3LW/A) running WatchOS 11.3 (22S553).
I noticed that the watch often misses heart measurements during meaningfully long segments of exercise sessions. This has been bugging me for a while and today I read an article that described perfectly, and much better than I could, what I am experiencing. Here is the article: https://apple.news/AK_QJyoLaQ1eaeySWHlkLPw
Is this a known issue that is being worked?
Thanks.
                    
                  
                
              
                
              
              
                
                Topic:
                  
	
		App & System Services
  	
                
                
                SubTopic:
                  
                    
	
		Health & Fitness
		
  	
                  
                
              
              
              
  
  
    
    
  
  
              
                
                
              
            
          
                    
                      Any idea to achieve reliable periodic Bluetooth data retrieval on iOS, even when the app is closed or killed.
                    
                  
                
                    
                      I am working on an Apple Watch companion app to an existing live iOS app. I am utilizing the heart rate tracking for an active 'self-care' sauna session. I say self-care in quotes because it's more self-care than a workout activity, but it is closely blurring the lines between the two.
I have come to understand that if a session truly isn't a workout, then you should not use workoutSession.startActivity. However the app needs to function entirely like a workout would. This is not a meditation application. Sauna is actually just one of many activity types supported in the app.
I have tried using extended runtime session, and there have been numerous issues with doing so. It is not nearly as robust for the user. For example, the active session is not prioritized by the watch's CPU. Now playing is no longer functional. Heart rate is far more inconsistent, and this variable is as critical as if it were in a workout.
I have tried using HKWorkoutSession, however I worry the app will be rejected by doing so. This method works most accurately to collect the right data for the user, and prioritizes system resources as expected. The app can be moved to the background as expected and continue to communicate with the iOS app.
What is the best way to move forward here. It almost feels like I am operating in a grey area with no real solution in place. Any assistance is greatly appreciated as we would like to follow all guidelines while producing a high quality experience for our users.
                    
                  
                
                    
                      Dear Apple Developers,
Could you kindly add the two following workout types to your Apple Watch? There are large communities that participate in both of these activities globally.
Rucking workout option. goruck.com
TRX suspension trainer option. trxtraining.com
Thank you for your consideration. This addition will make many people happy.
                    
                  
                
              
                
              
              
                
                Topic:
                  
	
		App & System Services
  	
                
                
                SubTopic:
                  
                    
	
		Health & Fitness