Swift - Using common SQLite database as persistent container.

Coding Sep 1, 2018

Using common SQLite database as persistent container with Xcode 8.3 and Swift 3.1.

    lazy var persistentContainer: NSPersistentContainer = {
        let sqlitePath = Bundle.main.url(forResource: "DATABASE_NAME", withExtension: "sqlite")
        
        if FileManager.default.fileExists(atPath: sqlitePath!.path) {
            
            let container = NSPersistentContainer(name: "DATABASE_NAME")
            
            let description = NSPersistentStoreDescription(url: sqlitePath!)
            description.shouldInferMappingModelAutomatically = true
            description.shouldMigrateStoreAutomatically = true
            container.persistentStoreDescriptions = [description]
            
            container.loadPersistentStores(completionHandler: { (storeDescription, error) in
                if let error = error as NSError? {
                    fatalError("Unresolved error \(error), \(error.userInfo)")
                }
            })
            return container
        }
        
        let container = NSPersistentContainer(name: "DATABASE_NAME")
        
        container.loadPersistentStores(completionHandler: { (storeDescription, error) in
            if let error = error as NSError? {
                fatalError("Unresolved error \(error), \(error.userInfo)")
            }
        })
        return container

    }()

Check it out on Github Gist

Tags

Great! You've successfully subscribed.
Great! Next, complete checkout for full access.
Welcome back! You've successfully signed in.
Success! Your account is fully activated, you now have access to all content.