2

I know there are some resources available for this but none of them clearly show the way how to do it properly.

I have already populated .sqlite database (MTrader.db) and i want to connect it to my swift project and load the data from the database into spinner.

I tried so many ways but it doesn't work. I try to edit lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? method in AppDelegete.swift as

if !NSFileManager.defaultManager().fileExistsAtPath(url.path!) {
            let sourceSqliteURLs = [NSBundle.mainBundle().URLForResource("MTrader", withExtension: "db")!]

            let destSqliteURLs = [self.applicationDocumentsDirectory.URLByAppendingPathComponent("MTrader.db")]

            var error:NSError? = nil
            for var index = 0; index < sourceSqliteURLs.count; index++ {
                NSFileManager.defaultManager().copyItemAtURL(sourceSqliteURLs[index], toURL: destSqliteURLs[index], error: &error)
            }
        }

For some reason above code isn't working. I copied my database file in my project. So is there any error with my code or any better way to use my existing database without creating new database and populating it?

2 Answers 2

6

First add libsqlite3.dylib to your Xcode project (in project settings/Build Phases/Link Binary with Libraries), then use something like fmdb, it makes dealing with SQLite a lot easier. It's written in Objective-C but can be used in a Swift project, too.

Then you could write a DatabaseManager class, for example...

import Foundation;

class DatabaseManager {

    private let dbFileName = "database.db"
    private var database:FMDatabase!

    init() {
        openDatabase()
    }

    func openDatabase() {
        let resourcePath = NSBundle.mainBundle().resourceURL!.absoluteString
        let dbPath = resourcePath?.stringByAppendingPathComponent(dbFileName)
        let database = FMDatabase(path: dbPath)

        /* Open database read-only. */
        if (!database.openWithFlags(1)) {
            println("Could not open database at \(dbPath).")
        } else {
            self.database = database;
        }
    }

    func closeDatabase() {
        if (database != nil) {
            database.close()
        }
    }

    func query(queryString:String) {
        if let db = database, q = db.executeQuery(queryString, withArgumentsInArray: nil) {
            while q.next() {
                let data = q.stringForColumn("columnName")
                // Do whatever here with fetched data, usually add it to an array and return that array
            }
        }
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanx for the complete code! Now its working i just waste whole day trying to edit that core data method. Thanx alot.
how can open database from here in write mode?
3

I have already populated .sqlite database

So you probably populated it using sqlite.

I try to edit lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator?

But there's your problem. NSPersistentStoreCoordinate is about Core Data, not sqlite. Core Data can use a sqlite backing store, but it can't open an arbitrary sqlite database file; you're not going to be able to use a sqlite database created independently, using sqlite, with Core Data. Use sqlite itself! The easiest way is with fmdb.

2 Comments

Here's a short example of using sqlite through fmdb with Swift, just to show that it can be done: github.com/mattneub/Programming-iOS-Book-Examples/blob/master/…
oops so thats the reason! I thought i can use .sqlite with editing above method. Thanx for quick reply and for the short example. then il use fmdb for this. Thanx matt!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.