SwiftData app crashes only when deployed via TestFlight

This SwiftData issue has me stumped. My app, when uploaded via cable works fine but when it is deployed via TestFlight it crashes immediately on startup while trying to do the first fetch for data.

Here is a screenshot of the crash report …
enter image description here

I’ve tried the following things to fix the issue:

  1. Disabled Swift Compiler - Code Generation configuration to No Optimization for both Debug and Release
  2. I tried calling the fetch from a task() modifier instead of onAppear()
  3. I deleted the app from the device before reinstalling it via TestFlight
  4. I tried it on a different device with a different iCloud account.

Here is the code that is calling the fetch() inside a ViewModel.

func refresh(_ ctx: ModelContext) {
    records.removeAll()
    
    let wRecs: [WeightRecord] = fetchAll(ctx)
    records.append(contentsOf: wRecs)
    
    let bpRecs: [BloodPressureRecord] = fetchAll(ctx)
    records.append(contentsOf: bpRecs)
    
    let mdRecs: [MedicationTakenRecord] = fetchAll(ctx)
    records.append(contentsOf: mdRecs)
    
    let bmRecs: [BowelMovementRecord] = fetchAll(ctx)
    records.append(contentsOf: bmRecs)
    
    let seRecs: [SideEffectRecord] = fetchAll(ctx)
    records.append(contentsOf: seRecs)
    
    let fdRecs: [FoodConsumedRecord] = fetchAll(ctx)
    records.append(contentsOf: fdRecs)
    
    let pmpRecs: [PumpChangeRecord] = fetchAll(ctx)
    records.append(contentsOf: pmpRecs)
    
    records.sort { lRec, rRec in
        lRec.recordedOn < rRec.recordedOn
    }
}

func fetchAll<R: PersistentModel & Record>(_ ctx: ModelContext) -> [R] {
    let fetchDescriptor = FetchDescriptor<R>(
        sortBy: [SortDescriptor(\.recordedOn)]
    )
    
    return (try? ctx.fetch(fetchDescriptor)) ?? []
}

Any ideas what might I am doing wrong?

  • 3

    Maybe it could help to replace try? with try and see if any error is thrown.

    – 




  • I’ll try that but it should just return an empty array if there was an error thrown. It shouldn’t crash.

    – 

  • I commented out the call to refresh() at startup and the app starts without any issues. In fact SwiftData is used elsewhere in the app without any problems. Its just the refresh() function above that causes issues – but only when deployed via TestFlight.

    – 

  • 1

    Delete the app from the device and delete iCloud manually. Then reinstall it could be a migration issue

    – 




  • 2

    Settings > User Logo at the top > iCloud > Manage Account Storage > App > Delete Data from iCloud.

    – 

Leave a Comment