Skip to content

Commit 0181a8c

Browse files
committed
Merge branch 'Docs-samplecode' of https://github.com/jasonpeterson/SQLite.swift into jasonpeterson-Docs-samplecode
2 parents 4b4dc65 + c8132a9 commit 0181a8c

File tree

1 file changed

+22
-2
lines changed

1 file changed

+22
-2
lines changed

Documentation/Index.md

Lines changed: 22 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -258,8 +258,29 @@ let path = NSSearchPathForDirectoriesInDomains(
258258
let db = try Connection("\(path)/db.sqlite3")
259259
```
260260

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

283+
263284
```swift
264285
var path = NSSearchPathForDirectoriesInDomains(
265286
.applicationSupportDirectory, .userDomainMask, true
@@ -273,7 +294,6 @@ atPath: path, withIntermediateDirectories: true, attributes: nil
273294
let db = try Connection("\(path)/db.sqlite3")
274295
```
275296

276-
277297
#### Read-Only Databases
278298

279299
If you bundle a database with your app (_i.e._, you’ve copied a database file
@@ -295,7 +315,7 @@ let db = try Connection(path, readonly: true)
295315
> See these two Stack Overflow questions for more information about iOS apps
296316
> with SQLite databases: [1](https://stackoverflow.com/questions/34609746/what-different-between-store-database-in-different-locations-in-ios),
297317
> [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"
318+
> We welcome changes to the above sample code to show how to successfully copy and use a bundled "seed"
299319
> database for writing in an app.
300320

301321
#### In-Memory Databases

0 commit comments

Comments
 (0)