Skip to content

Instantly share code, notes, and snippets.

@rd13
Last active September 11, 2022 17:00
Show Gist options
  • Save rd13/320b3fed4d5f10ab8ea833b3f9818980 to your computer and use it in GitHub Desktop.
Save rd13/320b3fed4d5f10ab8ea833b3f9818980 to your computer and use it in GitHub Desktop.
Copy database file from bundle to documents in Swift 3
func copyDatabaseIfNeeded() {
// Move database file from bundle to documents folder
let fileManager = FileManager.default
let documentsUrl = fileManager.urls(for: .documentDirectory,
in: .userDomainMask)
guard documentsUrl.count != 0 else {
return // Could not find documents URL
}
let finalDatabaseURL = documentsUrl.first!.appendingPathComponent("SQL.sqlite")
if !( (try? finalDatabaseURL.checkResourceIsReachable()) ?? false) {
print("DB does not exist in documents folder")
let documentsURL = Bundle.main.resourceURL?.appendingPathComponent("SQL.sqlite")
do {
try fileManager.copyItem(atPath: (documentsURL?.path)!, toPath: finalDatabaseURL.path)
} catch let error as NSError {
print("Couldn't copy file to final location! Error:\(error.description)")
}
} else {
print("Database file found at path: \(finalDatabaseURL.path)")
}
}
@AegerBorder
Copy link

Great function - thank you! Good to go on working on the database by using Sqlite.Swift.
By the way: this code still works fine with Swift 4 - no necessity to "update" the code in any way.

@darthpelo
Copy link

Thanks for sharing it!

@khacdat1994
Copy link

thank for resolve

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment