Search code examples
swiftuikitswiftdata

How to properly initiate ModelContainer(SwiftData) in SceneDelegate?


It's my very first time applying SwiftData on an UIKit project. My CustomerService class takes a ModelContext object.

class CustomerService {
    
    private let context: ModelContext
    
    init(context: ModelContext) {
        self.context = context
    }
//... CRUD functions
}

Need to get it somehow from SceneDelegate.

    class SceneDelegate: UIResponder, UIWindowSceneDelegate {

    var window: UIWindow?
    
    var modelContainer: ModelContainer!
    

    func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
        
        // modelContainer = ???? how
        
        guard let windowScene = (scene as? UIWindowScene) else { return }
        let window = UIWindow(windowScene: windowScene)
        let customerListVC = CustomerListVC(viewModel: CustomerListViewModel(customerService: CustomerService(context: modelContainer.mainContext)))
        let navigationController = UINavigationController(rootViewController: customerListVC)
        window.rootViewController = navigationController
    

        self.window = window
        window.makeKeyAndVisible()
     }
}

Solution

  • First you need a model:

    @Model
    class User { }
    

    Then you can initialize the ModelContainer like this :

    var modelContainer: ModelContainer?
    
    func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
       ///
       modelContainer = try? ModelContainer(for: User.self)
       ///
    }