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)") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for sharing it!