iOS app with Swift + SQLite Cipher

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:

  1. Create a new Swift project and then close XCode
  2. Go to Terminal and from app folder create a pod file, using: pod init
  3. Edit Podfile and add the following line: pod 'SQLCipher'
  4. From Terminal install the pod, using: pod install
  5. Open the xcworkspace file and you will see both the project and Pods in XCode
  6. In General tab add under Embedded Binaries the SQLCipher.frameworkiOS
  7. Import the SQLCipher in the header of the swift file, like: import SQLCipher
  8. 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")
}

Categories

Archive