Last active
September 11, 2022 17:00
-
-
Save rd13/320b3fed4d5f10ab8ea833b3f9818980 to your computer and use it in GitHub Desktop.
Copy database file from bundle to documents in Swift 3
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)") | |
} | |
} |
Thanks for sharing it!
thank for resolve
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.