Friday, April 10, 2015

Overview

When you want to persist data on a mobile device, you usually have to use its internal database. For iPhones and other Apple mobile devices, that’s sqlite3. For this post, we’ll look at the beautifully written SwiftData library found here on github.

Content

Simply download the SwiftData.swift file and copy it into your project. You also need the libsqlite3.dylib framework in your project, so make sure you add it. That framework is in C, so you have to add #import "sqlite3.h" to the Briding-Header.h. Now you’re ready to start.

To create a new table.

1
2
3
4
5
6
7
8
9
10
if let err = SD.createTable("Cities", 
    withColumnNamesAndTypes: [
     "Name": .StringVal,
     "Population": .IntVal,
     "IsWarm": .BoolVal,
     "FoundedIn": .DateVal]) {
  // there was an error during this function, handle it here
} else {
  // no error, the table was created successfully
}

To delete a table.

1
let err = SD.deleteTable("TableName")

To find all tables.

1
let (tables, err) = SD.existingTables()

To insert.

1
2
3
4
5
6
7
8
9
10
11
12
13
//from user input
let name: String = //user input
let population: Int = //user input
let isWarm: Bool = //user input
let foundedIn: NSDate = //user input

if let err = SD.executeChange(
    "INSERT INTO Cities (Name, Population, IsWarm, FoundedIn) VALUES (?, ?, ?, ?)", 
    withArgs: [name, population, isWarm, foundedIn]) {
    //there was an error during the insert, handle it here
} else {
    //no error, the row was inserted successfully
}

To query a table.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
let (resultSet, err) = SD.executeQuery("SELECT * FROM Cities")
if err != nil {
    //there was an error during the query, handle it here
} else {
    for row in resultSet {
        if let name = row["Name"]?.asString() {
            println("The City name is: \(name)")
        }
        if let population = row["Population"]?.asInt() {
            println("The population is: \(population)")
        }
        if let isWarm = row["IsWarm"]?.asBool() {
            if isWarm {
                println("The city is warm")
            } else {
                println("The city is cold")
            }
        }
        if let foundedIn = row["FoundedIn"]?.asDate() {
            println("The city was founded in: \(foundedIn)")
        }
    }
}

Random Posts