Skip to content

Commit 304c39d

Browse files
committed
added sample code for copying a 'seed' database
1 parent d13baed commit 304c39d

File tree

1 file changed

+23
-1
lines changed

1 file changed

+23
-1
lines changed

Documentation/Index.md

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -258,6 +258,28 @@ let path = NSSearchPathForDirectoriesInDomains(
258258
let db = try Connection("\(path)/db.sqlite3")
259259
```
260260

261+
If you have bundled it your application, you can use FileManager to copy it to the Documents directory:
262+
263+
```swift
264+
func copyDatabaseIfNeeded(sourcePath : String) -> Bool {
265+
var destinationPath = NSSearchPathForDirectoriesInDomains(
266+
.documentDirectory, .userDomainMask, true
267+
).first!
268+
destinationPath = destinationPath + "/db.sqlite3"
269+
let databaseExistsWhereNeeded = FileManager.default.fileExists(atPath: destinationPath)
270+
if (!databaseExistsWhereNeeded) {
271+
do {
272+
try FileManager.default.copyItem(atPath: sourcePath, toPath: destinationPath)
273+
print("db copied")
274+
}
275+
catch {
276+
print("error during file copy: \(error)")
277+
}
278+
}
279+
return true
280+
}
281+
```
282+
261283
On OS X, you can use your app’s **Application Support** directory:
262284

263285
```swift
@@ -295,7 +317,7 @@ let db = try Connection(path, readonly: true)
295317
> See these two Stack Overflow questions for more information about iOS apps
296318
> with SQLite databases: [1](https://stackoverflow.com/questions/34609746/what-different-between-store-database-in-different-locations-in-ios),
297319
> [2](https://stackoverflow.com/questions/34614968/ios-how-to-copy-pre-seeded-database-at-the-first-running-app-with-sqlite-swift).
298-
> We welcome sample code to show how to successfully copy and use a bundled "seed"
320+
> We welcome changes to the above sample code to show how to successfully copy and use a bundled "seed"
299321
> database for writing in an app.
300322

301323
#### In-Memory Databases

0 commit comments

Comments
 (0)