Post

Replies

Boosts

Views

Activity

Reply to How to accurately query HKWorkout segment data
Thank you for sharing this article — it directly touches on the issue I’m currently facing. I have actually tried both approaches mentioned: 1.Using .distanceWalkingRunning or .distanceCycling samples to accumulate distance and determine per-kilometer (or per-mile) ranges. This is a reasonable suggestion, but it comes with a major drawback. For example, processing a 100 km cycling workout produces a very large number of samples, and the overhead becomes even greater when handling multiple workouts in bulk. In other words, this method is valid but not efficient. 2.As edorphy pointed out, Apple Watch’s Activity app does record per-kilometer and per-mile split points as HKWorkoutEvents. In my own testing, these event markers are actually more accurate than the splits derived from accumulating .distanceWalkingRunning or .distanceCycling samples. This leads to a simple but important question: how can developers make effective use of the HKWorkoutEvents that Apple Watch already records and stores in HealthKit? In other words, is there a way to reliably distinguish these events — even when they sometimes overlap — so that they can be used as accurate split markers? I strongly believe that the iOS Fitness app is not inefficiently recalculating splits by iterating through every distance sample. There must be a more optimal solution. I would greatly appreciate more professional guidance on this point, and I believe a clear answer here could benefit many HealthKit developers who want to implement split statistics more efficiently.
Sep ’25
Reply to Crash by SwiftData MigarionPlan
Hello, first of all, thank you for your reply. The headache of this problem is that it cannot be reproduced in Xcode. However, I seem to have found some clues recently. In enum MeSchemaV5: VersionedSchema { ... } , I listed all the Model definition codes. But outside this enum, I also defined all the Models (all the codes are exactly the same), and did not use typealias to specify the Model. I guess it may be due to this reason that when the ModelContainer is initialized, the Model of the schema all points to the Model outside the enum, and the Model corresponding to SchemaV5 is not found during the execution of MigraitonPlan, so the error "Error.loadIssueModelContainer" is reported. I tried to delete the Model definition code outside the enum and use typealias to specify the corresponding Model. typealias HealthDataList = MeSchemaV5.HealthDataList typealias HealthDataStatistics = MeSchemaV5.HealthDataStatistics typealias HeartZoneData = MeSchemaV5.HeartZoneData typealias UserSettingTypeFor = MeSchemaV5.UserSettingTypeFor typealias SleepDataSource = MeSchemaV5.SleepDataSource ... The problem seems to have improved. Most of the time, the migration operation can be completed normally without crashes. However, there are still a small number of users who report that "Error.loadIssueModelContainer" sometimes appears. But I'm not sure if it is related to this. At the same time, I don't know if you can provide a sample code on how to use MigraitonPlan correctly. There is really little content in the official documentation for this area. I hope to get your help to learn how to use MigraitonPlan correctly, as well as some related precautions. In addition, I have never encountered the error you mentioned, "error: Attempting to retrieve an NSManagedObjectModel version checksum while the model is still editable. This may result in an unstable verison checksum. Add model to NSPersistentStoreCoordinator and try again.". However, when I initialized ModelContainer using the new method, this error appeared and can be reproduced in Xcode. How do I submit a feedback report? Finally, thank you again for your help.
Jul ’24
Reply to Crash by SwiftData MigarionPlan
I found something interesting. In the demo I uploaded, if MigrationPlan is enabled when the version is updated, an error will always be reported. If MigrationPlan is not used when ModelCotainer is initialized, no matter how the Model is modified between different versions, no error will be reported. So I deleted MigrationPlan in my App and uploaded it to TestFlight. Unfortunately, the error of SwiftData.SwiftDataError._Error.loadIssueModelContainer appeared.
Jul ’24
Reply to Crash by SwiftData MigarionPlan
I just tried logging an error.localizedDescription in TestFlight and got : Could not create ModelContainer: The operation couldn’t be completed. I also tried adding -com.apple.CoreData.MigrationDebug 1 to the launch arguments, but there was no "CoreData: error: ..." in the Xcode console. I created a new project and copied the MigraitonPlan-related code from my code into it and uploaded it to Github. TestDemo
Jul ’24
Reply to Crash by SwiftData MigarionPlan
I continued to test other versions. Before and after the migration, ModelVersionIdentifiers was always "1.0.0" init() { let schema = Schema([ WorkoutList.self, HealthDataStatistics.self, SportsDataStatistics.self, UserSettingTypeFor.self, TodayRingData.self, TodayHealthData.self, SleepDataSource.self, WorkoutTargetData.self, WorkoutStatisticsForTarget.self, HealthDataList.self, SleepStagesData.self, WorkoutDetailData.self, HeartZoneData.self, WorkoutSegmentData.self, WorkoutMaxMinRangeData.self, WorkoutHeartZoneData.self ]) do { container = try ModelContainer( for: schema, migrationPlan: MeMigrationPlan.self ) print("ModelContainer initialized successfully") print("container \(container.self)") print("containerVersion \(container.schema.version)") print("containerEncodingVersion \(container.schema.encodingVersion)") print("containerMigrationPlan \(container.migrationPlan)") print("containerConfigurations \(container.configurations)") } catch { print("Error initializing model container: \(error)") fatalError("Failed to initialize model container.") } } Log output after migration: ModelContainer initialized successfully container SwiftData.ModelContainer containerVersion 1.0.0 containerEncodingVersion 1.0.0 containerMigrationPlan Optional(Me.MeMigrationPlan) containerConfigurations [ModelConfiguration name: default url: file:///private/var/mobile/Containers/Shared/AppGroup/0D641150-923C-4A26-B908-1FCEA6012721/Library/Application%20Support/default.store allowsSave: true isStoredInMemoryOnly: false cloudKitDatabase: CloudKitDatabase(_automatic: true, _none: false, _privateDBName: nil) cloudKitContainerIdentifier: nil groupContainer: GroupContainer(_automatic: true, _none: false, _identifier: nil) groupAppContainerIdentifier: Optional("group.XXXXXXXXX.kookybread.me")]
Jul ’24
Reply to Crash by SwiftData MigarionPlan
I tested in Xcode today and found that when the migration started, the NSStoreModelVersionHashesVersion of the previous version of the Schema seemed to always be "1.0.0". Although the Models corresponded to Schema.Version(3, 0, 0) ... CoreData: annotation: Incompatible version schema for persistent store 'file:///private/var/mobile/Containers/Shared/AppGroup/48F39567-A54A-45A6-B51F-EBB5064E488C/Library/Application%20Support/default.store'. store metadata = { NSPersistenceFrameworkVersion = 1345; NSStoreModelVersionChecksumKey = "m47Q+vHOr0gMrRL9ogWBvunjLYZwmfrt0PDX73TO/oA="; NSStoreModelVersionHashes = { HealthDataList = {length = 32, bytes = 0x27b73968 fe755a8f 28dd4224 1692184d ... e7762ec3 66e4f0fa }; HealthDataStatistics = {length = 32, bytes = 0x7b1c108d 3578e7df 22035d15 b4f2eadf ... 4e150ac4 337f17f8 }; SleepDataSource = {length = 32, bytes = 0x293b98b8 9ea8499c f7c61923 afd393a3 ... 7c034d3b d8928042 }; SportsDataStatistics = {length = 32, bytes = 0x0b67e997 dddfddbd 5b53cd40 c58993f5 ... 77064cd6 b53b1b1b }; TodayHealthData = {length = 32, bytes = 0xfb6de2ab 2fd504e6 88989a57 bb77a1a2 ... 56c03fca 0973076e }; TodayRingData = {length = 32, bytes = 0x2c0a63ed 7babcb9a d206cd3e 62a35ca8 ... ee3ca37a 14b3b9ce }; UserSettingTypeFor = {length = 32, bytes = 0xdc8b892a b46ce5b3 707263dd ba511389 ... d7899956 9e8d5890 }; WorkoutList = {length = 32, bytes = 0xe510f3ad 374714f1 2845e983 d1b53a9b ... 4761cabf 477ac79b }; WorkoutStatisticsForTarget = {length = 32, bytes = 0xe4e7fef0 daf11afe b9601a0f 5374446f ... 06e0be97 eccf372b }; WorkoutTargetData = {length = 32, bytes = 0x4f636c57 b8de4f32 5be80c23 1bb882a1 ... 655be445 20d96f1a }; }; NSStoreModelVersionHashesDigest = "Qq+tCNnYs1Cq87uFu98DSiOor6rB8Noz6mfrEGibCFWNe0Y3uRqyok4sbz4LVhYpHUl3tgw9jRw6rrm6iimpxA=="; NSStoreModelVersionHashesVersion = 3; NSStoreModelVersionIdentifiers = ( "1.0.0" ); NSStoreType = SQLite; NSStoreUUID = "4DB70733-02E9-4BD7-8037-05AE5EE3DEDA"; "_NSAutoVacuumLevel" = 2; } ...
Jul ’24
Reply to Crash by SwiftData MigarionPlan
I searched the Internet for a long time, and almost all of them are related to CloudKit, but I don't use anything related to CloudKit. Another thing is that I use some Codable structures and @Attribute(.unique) in the definition of some of my models. I wonder if this has any impact on this?
Jun ’24
Reply to Crash by SwiftData MigarionPlan
I tried using sysdiagnose but it was too hard for me. This is how I caught the error: import SwiftUI import HealthKit import SwiftData import os.log @main struct MeApp: App { @StateObject var viewModel = ViewModel() @StateObject private var entitlementManager: EntitlementManager @StateObject private var purchaseManager: PurchaseManager @StateObject var sessionManager = SessionManager() let colors: [Color] = [ .introGreen, .introBlue] @State var sharedModelContainer: ModelContainer? @State var crashInfo: String = "No Crash" // 初始化方法 init() { let entitlementManager = EntitlementManager() let purchaseManager = PurchaseManager(entitlementManager: entitlementManager) self._entitlementManager = StateObject(wrappedValue: entitlementManager) self._purchaseManager = StateObject(wrappedValue: purchaseManager) } var body: some Scene { WindowGroup { VStack{ if let container = sharedModelContainer{ ContentView() .environmentObject(viewModel) .environmentObject(queryData) .environmentObject(ringsDataQuery) .environmentObject(darkModeSettings) .environmentObject(recordsQuery) .environmentObject(sst) .environmentObject(hrQuery) .environmentObject(purchaseManager) .environmentObject(entitlementManager) .environmentObject(sessionManager) .modelContainer(container) .preferredColorScheme(darkModeSettings.isDarkModeEnabled ? .dark : nil) .task { await loadImage() await loadImage2() await purchaseManager.updatePurchasedProducts() sessionManager.startSession() } } else { VStack{ Image("Failed") .resizable() .scaledToFit() .frame(width: 100) Text("Er...There is something wrong.") .font(.system(size: 36)) .fontWeight(.bold) .multilineTextAlignment(.center) .foregroundStyle(LinearGradient(colors: colors, startPoint: .leading, endPoint: .trailing)) Text(crashInfo) .font(.system(size: 12)) .padding(20) } .padding(.horizontal,20) .preferredColorScheme(.dark) .transition(AnyTransition.move(edge: .bottom).animation(.spring(duration: 1.5))) .transition(AnyTransition.opacity.animation(.spring(duration: 1.5))) } } .onAppear{ let log = Logger(subsystem: "Kookybread.Me", category: "modelContainer") do { let schema = Schema([ HealthDataList.self, HealthDataStatistics.self, HeartZoneData.self, UserSettingTypeFor.self, SleepDataSource.self, SleepStagesData.self, SportsDataStatistics.self, TodayHealthData.self, TodayRingData.self, WorkoutDetailData.self, WorkoutHeartZoneData.self, WorkoutList.self, WorkoutMaxMinRangeData.self, WorkoutSegmentData.self, WorkoutStatisticsForTarget.self, WorkoutTargetData.self, AvatarImage.self, NickName.self ]) sharedModelContainer = try ModelContainer( for: schema, migrationPlan: MeMigrationPlan.self ) print("ModelContainer initialized successfully") } catch { log.error("Failed to initialize model container: \(error, privacy: .public)") crashInfo = "Error: \(error.self)" } } } } }
Jun ’24
Reply to Crash by SwiftData MigarionPlan
Use "-com.apple.CoreData.SQLDebug 1" to output the log in the Xcode console: CoreData: annotation: Completed persistent history metadata tables update CoreData: annotation: Updating metadata CoreData: annotation: Finished updating metadata CoreData: annotation: Starting inferred mapping validation CoreData: annotation: Executing inferred mapping validation: IEM_Transform_WorkoutList CoreData: annotation: Finished inferred mapping validation CoreData: annotation: Committing formal transaction CoreData: annotation: Finished committing formal transaction CoreData: annotation: Checkpointing WAL journal CoreData: annotation: Finished checkpointing WAL journal CoreData: annotation: Successfully completed lightweight migration on connection CoreData: annotation: Migration step 0.0 'Total migration time (on connection)' took 0.05 seconds CoreData: annotation: Migration step 2.0 'Total formal transaction time' took 0.04 seconds CoreData: annotation: Migration step 2.5 'Execution of entity schema and data migration statements' took 0.02 seconds CoreData: annotation: (migration) in-place migration completed successfully in 0.06 seconds CoreData: annotation: (migration) Automatic schema migration succeeded for store
Jun ’24