From 3d4ee9ee53858afc3fe884d9dd7729f7a8186fd5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 3 Mar 2016 14:42:57 +0100 Subject: [PATCH] FAQ: How do I open a database stored as a resource of my application? --- README.md | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index 87769e6c3..b951d2ff2 100644 --- a/README.md +++ b/README.md @@ -2374,21 +2374,21 @@ FAQ ```swift var configuration = Configuration() configuration.readonly = true - let dbPath = NSBundle.mainBundle().URLForResource("db", withExtension: "sqlite")!.path! - let dbQueue = DatabaseQueue(path: dbPath, configuration: configuration) + let dbPath = NSBundle.mainBundle().pathForResource("db", ofType: "sqlite")! + let dbQueue = try! DatabaseQueue(path: dbPath, configuration: configuration) ``` If the application should modify the database, then you need to copy it to a place where it can be modified. For example, in the Documents folder: ```swift let fm = NSFileManager.defaultManager() - let documentsURL = try! fm.URLForDirectory(.DocumentDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: true) - let dbResourceURL = NSBundle.mainBundle().URLForResource("db", withExtension: "sqlite")! - let dbURL = documentsURL.URLByAppendingPathComponent(dbResourceURL.lastPathComponent!) - if !fm.fileExistsAtPath(dbURL.path!) { - try! fm.copyItemAtURL(dbResourceURL, toURL: dbURL) + let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] + let dbPath = (documentsPath as NSString).stringByAppendingPathComponent("db.sqlite") + if !fm.fileExistsAtPath(dbPath) { + let dbResourcePath = NSBundle.mainBundle().pathForResource("db", ofType: "sqlite")! + try! fm.copyItemAtPath(dbResourcePath, toPath: dbPath) } - let dbQueue = DatabaseQueue(path: dbURL.path!) + let dbQueue = DatabaseQueue(path: dbPath) ```