If you need an iOS app done in Swift that requires an encrypted SQLite database, these are the steps for a simple and under full control solution:
- Create a new Swift project and then close XCode
- Go to Terminal and from app folder create a pod file, using: pod init
- Edit Podfile and add the following line: pod 'SQLCipher'
- From Terminal install the pod, using: pod install
- Open the xcworkspace file and you will see both the project and Pods in XCode
- In General tab add under Embedded Binaries the SQLCipher.frameworkiOS
- Import the SQLCipher in the header of the swift file, like: import SQLCipher
- Here is an example of a method that creates and tests an encrypted SQLite database:
// db pointer
var db: COpaquePointer = nil
// get the path of database
let dir : NSString = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .AllDomainsMask, true).first!
let dbPath = dir.stringByAppendingPathComponent("db.sqlite3")
// create and open the database
sqlite3_open_v2(dbPath, &db, SQLITE_OPEN_CREATE | SQLITE_OPEN_READWRITE | SQLITE_OPEN_FULLMUTEX, nil)
// encrypt the database using a key
let key = "any_string_you_like"
sqlite3_key(db, key, Int32(key.utf8.count))
// test database and
let sql = "CREATE TABLE test (id INTEGER, field1 TEXT, field2 TEXT)"
if (sqlite3_exec(db, sql, nil, nil, nil) != SQLITE_OK) {
print("error")
}