sqlite3_open works in swift playground not swift app

Viewed 758

when I run the following code in swift playground it returned success. When I copied it to my Xcode project it returned failure. I figure it has something to do with the path so I googled and tried, path.cString(using: String.Encoding.utf8) but still no luck. what I don't understand is why it works in playground but not in the app itself.

var db: OpaquePointer? = nil;
let path:String="/Users/williamstorey/Documents/db182.db"
if sqlite3_open(path ,&db) == SQLITE_OK {
   print("SUCCESS")
} else {
   print("FAILURE");
}
1 Answers

You shouldn’t just check if it’s SQLITE_OK, but rather save the return code and examine the value returned, if it’s not SQLITE_OK. If you don't look at the actual return code value, you're just guessing what the problem might be.

But the most likely problem is that your app is sandboxed and can’t just open the file there. You should build the URL dynamically, and you'll get a safe file URL/path:

let fileURL = try! FileManager.default
    .url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
    .appendingPathComponent("db182.db")

print(fileURL.path)

let returnCode = sqlite3_open(fileURL.path, &db)

That will result in something like:

/Users/williamstorey/Library/Containers/com.domain.MyApp/Data/Documents/db182.db

Frankly, you might want to use the .applicationSupportDirectory rather than the .documentDirectory. See File System Programming Guide: The Library Directory Stores App-Specific Files. Also see About App Sandbox.

Related