Copy a pre-populated SQLite file to documents directory for Core Data using Swift

Here is a quick snippet that shows how to check for the existence of a sqlite file in the documents directory and how to copy the file from the app bundle to the documents directory if it does not exists. This should be done before adding the persistent store to the persistent store coordinator ensure that there is pre-populated data
.

let storePath : NSString = self.applicationDocumentsDirectory().stringByAppendingPathComponent("MyDb.sqlite")
        let fileManager : NSFileManager = NSFileManager.defaultManager()
        var fileCopyError:NSError? = NSError()
        if !fileManager.fileExistsAtPath(storePath) {
            let defaultStorePath : NSString! = NSBundle.mainBundle().pathForResource("MyDb", ofType: "sqlite")
            if(defaultStorePath) {
                fileManager.copyItemAtPath(defaultStorePath, toPath: storePath, error: &fileCopyError)
            }
        }

Leave a Reply

Your email address will not be published. Required fields are marked *