SwiftData Fatal error: failed to find a currently active container

I'm new to Apple development and decided to learn using SwiftData and Xcode 15 beta 4 (though I'm starting to think I don't need that extra challenge). I've worked through many issues--with you all's help--but this is one I can't figure out and hasn't shown up in my searches.

I'm working on the traditional task list app (with a Task model). I've tried several approaches to app structure, but each time I eventually hit this same error. It doesn't happen when I set up the new Xcode project, but eventually it does. I've cleaned the build folder, restarted the Simulator, and even rebooted the Macbook I'm working on.

Here's what happens when I click Product > Run:

  • the app builds successfully

  • the Simulator displays a white screen as expected

  • then the error appears.

Here are the error messages:

In the debug area it says:

SwiftData/ModelContainer.swift:159: Fatal error: failed to find a currently active container for Task
Failed to find any currently loaded container for Task)

and in the warning in the editor says Thread 1: Fatal error: failed to find a currently active container for Task

The debugger is highlighting this line in the call stack (not sure if that's useful as a newbie):

#7	0x0000000100bb6d90 in Task.init(id:title:priority:) at /var/folders/3v/q8g4z9bx4lb9z6t7mhgwgghw0000gn/T/swift-generated-sources/@__swiftmacro_10BadgerTool4Task5ModelfMm_.swift:2

Here's the code:

The Task model isn't complex:

//  Task.swift
import Foundation
import SwiftData

@Model
class Task {
    @Attribute(.unique) var id: UUID
    var title: String
    var priority: String
    
    init(id: UUID = UUID(), title: String, priority: String = "None") {
        self.id = id
        self.title = title
        self.priority = priority
    }
}

I have the model container set in the context of the highest view:

//  BadgerToolApp.swift
import SwiftUI
import SwiftData

@main
struct BadgerToolApp: App {
    var body: some Scene {
        WindowGroup {
            NavView()
            .modelContainer(for: Task.self)
        }
    }
}

I tried moving all other views one layer down (which is why the unnecessary NavView is there):

//  NavView.swift
import SwiftUI
import SwiftData

struct NavView: View {
    @State var selectedCollection: Collection?
    @State var selectedTask: Task?
    
    var body: some View {
        NavigationSplitView(
            sidebar: {
                SideBarView(selectedCollection: $selectedCollection, selectedTask: $selectedTask)
            },
            content: {
                ContentListView(selectedCollection: $selectedCollection, selectedTask: $selectedTask)
            },
            detail: {
                TaskDetailView(selectedCollection: $selectedCollection, selectedTask: $selectedTask)
            }
        )
    }
}

Trying to isolate my mistake

I removed everything else related to SwiftData (except for the imports) and gave my views hard-coded data for the simulator like this:

//  SideBarView.swift
import SwiftUI
import SwiftData

struct SideBarView: View {
    @Binding var selectedCollection: Collection?
    @Binding var selectedTask: Task?
    let collections = presetCollections //temp data

    var body: some View {
            List(collections, id: \.id, selection: $selectedCollection){ collection in
                NavigationLink(collection.name, value: collection)
            }
            List{
                Text("All Tasks")
                Text("Settings")
            }
            .navigationTitle("Collections")
    }

}

Everything works as expected if

  • I comment out the .modelContainer() modifier on the call to NavView view
  • I change the Task definition from the @Model class to a regular struct like this:
//  Task.swift
// with @Model removed

import Foundation

struct Task: Hashable {
    var id: UUID
    var title: String
    var priority: String
    
    init(id: UUID = UUID(), title: String, priority: String = "None") {
        self.id = id
        self.title = title
        self.priority = priority
    }
}

What am I missing? Could it be a bug?

Thanks for your help!

Answered by Haleixo in 760288022

I do really think the container is not correctly initiated yet at that point? Initializing the container prior to passing it in seems to fix it, like so:

@main
struct MyApp: App {
    
    let modelContainer: ModelContainer
    
    init() {
        do {
            modelContainer = try ModelContainer(for: Item.self)
        } catch {
            fatalError("Could not initialize ModelContainer")
        }
    }
    
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
        .modelContainer(modelContainer)
    }
}

Yeah, I had the same issue myself. When the model is created, the app crashes as it can't find an available CloudKit container. If you have CloudKit enabled, it requires all properties to be optional. Making all properties and relationships optional fixed the issue for me.

Could you show the file where the ModelContainer was set up? That would help find the issue.

I found that it works in a simulator, but not on an iPhone or the preview(might be a beta bug). Here is my code:

import SwiftUI
import SwiftData

struct DiscoverView: View {
    
    @Environment(\.modelContext) private var context
    @Query private var rootBeers: [RootBeerData]
    var body: some View{
        NavigationStack{
            List(rootBeers) { rootbeer in
                discoverSumary(title: rootbeer.name, desc: rootbeer.desc, icon: rootbeer.icon)
            }
            .navigationTitle("Discover")
            .listStyle(.inset)
        }
    }
}

#Preview {
    DiscoverView()
}

And this is the data model:

import Foundation
import SwiftData
import SwiftUI

@Model
class RootBeerData{
    var name: String
    var desc: String
    var icon: String
    
    init(name: String, desc: String, icon: String) {
        self.name = name
        self.desc = desc
        self.icon = icon
    }
}

And don't forget to add the .modelContainer(for: RootBeerData.self) modifier to ContentView()

I was trying to test this and am getting the error if I initialize the item in the View. Works fine if I initialize the model in the view's .onAppear. I am not knowledgeable on this subject, but could it be that the container is not ready yet until the view appears? Or I might be using this wrong to beging with...

Doesn't work:

struct ContentView: View {
    
    @Environment(\.modelContext) private var modelContext
    
    @State var item: Item?
    
    init() {
        freezer = Item(name: "My Item")
    }
    
    var body: some View {
            Text(item?.name ?? "No item")
    }
}

Works:

struct ContentView: View {
    
    @Environment(\.modelContext) private var modelContext
    
    @State var item: Item?
    
    var body: some View {
            Text(item?.name ?? "No item")
        .onAppear(perform: {
              item = Item(name: "Test Item")
        })
    }
}
Accepted Answer

I do really think the container is not correctly initiated yet at that point? Initializing the container prior to passing it in seems to fix it, like so:

@main
struct MyApp: App {
    
    let modelContainer: ModelContainer
    
    init() {
        do {
            modelContainer = try ModelContainer(for: Item.self)
        } catch {
            fatalError("Could not initialize ModelContainer")
        }
    }
    
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
        .modelContainer(modelContainer)
    }
}
10

Thanks, that seems to do it.

The other solution—and the one I’m least happy with—is to completely delete the app and its data from the simulator and restart the simulator. I still can’t make the error happen reliably, so it’s hard to call it a bug.

Thanks for all your help!

I had the same issue after the XCode beta 5 update.

My issue has three models in an array, so a slightly different solution:

import SwiftData import SwiftUI

@main struct SurvAIApp: App {

let modelContainer: ModelContainer

init() {
	do {
		modelContainer = try ModelContainer(for: [ViewModel1.self,ViewModel2.self, ViewModel3.self])
	} catch {
		fatalError("Could not initialize ModelContainer")
	}
}
var body: some Scene {
    WindowGroup {
        NavigationStack {
            ContentView()
        }
        .modelContainer(modelContainer )

    }
}

I had this issue after a change in the model. In my case, removing the app and re-installing did the trick.

I face the same issue in modifying my initial model and trying to insert data with additional values. I believe SwiftData requires a migration of schema after this but a simple solution for me was to delete the app and let XCode recreate it on both simulator and iPhone.

I have the same problem. After changing data structure, I'm getting "SwiftData Fatal error: failed to find a currently active container". @beninzi, how do you delete the app and 'let Xcode recreate it?" Thank you

Found the solution, but can't post the link here, below is the implementation, easy and clear:

@Model
class User {
    var name: String

    init(name: String) {
        self.name = name
    }
}

struct EditingView: View {
    @Environment(\.modelContext) var modelContext
    @Bindable var user: User

    var body: some View {
        Form {
            TextField("Name", text: $user.name)
        }
    }
}

#Preview {
    let config = ModelConfiguration(isStoredInMemoryOnly: true)
    let container = try! ModelContainer(for: User.self, configurations: config)

    let user = User(name: "Test User")
    return EditingView(user: user)
        .modelContainer(container)
}

The core concept is, you must create the modelContainer first, then create the User, finally create the View pass the user in. Since a swift data model instance can not live without a model container

I'm refactoring my old iPhone app that uses Storyboards and AppDelegate to use SwiftData.

When I launch the app, I hit the issue because my ModelContainer in my "quick sanity check integration" was being created after static variables containing "default recipes".

I had to use the custom storyboard initializer to work around this issue, until I revamp the launch screen from a UIViewController backed by a storyboard to a SwiftUI view and the new app structure.

This uses the instantiateViewController(identifier:creator:) variant of the Storyboard class so that I can inject the dependencies for SwiftData.

https://developer.apple.com/documentation/uikit/uistoryboard/3213989-instantiateviewcontroller

On start I have this logic in application(didFinishLaunchingWithOptions:

let dataContainer = DataContainer(enableCloudKit: false, isStoredInMemoryOnly: false)
let userSettings = UserSettings()
let recipeHelper = RecipeHelper(userSettings: userSettings)

let storyboard = UIStoryboard(name: "Main", bundle: nil)
let measureVC = storyboard.instantiateViewController(identifier: "MeasureViewController") { coder in
    return MeasureViewController(coder: coder, userSettings: userSettings, recipeHelper: recipeHelper, dataContainer: dataContainer)
}

The offending code was a SwiftData static variable.

static let harioV60_size1 = CoffeeRecipe(
    dateCreated: .now,
    dateModified: .now,
    dateBrewed: nil,
    title: "Hario V60",
    brewMethod: .harioV60_Size1,
    defaultRecipe: true,
    waterToCoffeeRatio: 16.2,
    coffeeWeight: 21,
    waterWeight: 340,
    bloomRatio: 2,
    bloomTime: 30,
    pourTime: 2.5 * 60,
    drainTime: 3 * 60
)
SwiftData Fatal error: failed to find a currently active container
 
 
Q