Daniele B
Daniele B

Reputation: 20412

Swift: how to populate UITableView with SQLite column

I would like to populate a basic UITableView (one-row cells) with a one-column coming from a SQLite database query.

How can I do that in Swift?

Upvotes: 0

Views: 3999

Answers (1)

Daniele B
Daniele B

Reputation: 20412

I found the solution using the SQLite.Swift library! Very simple actually.

Here is an example with an sqlite database of cities, using a UITextField to type the name of the city, and a UITableView to display the matching results while typing.

import UIKit
import SQLite

let path = NSBundle.mainBundle().pathForResource("cities", ofType: "sqlite")! // in case of a sqlite file called 'cities.sqlite'
// N.B. the sqlite file needs to be added to the project and to the application target

let db = Database(path, readonly: true)

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

    var cities : [String]?

    @IBOutlet weak var searchTextField: UITextField!
    @IBOutlet var resultsTableView : UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()
        searchTextField.addTarget(self, action: "textFieldDidChange:", forControlEvents: UIControlEvents.EditingChanged)
    }

    func textFieldDidChange(textField: UITextField) {
        cities = [String]()
        for row in db.prepare("SELECT name FROM cities WHERE name LIKE \"%"+textField.text+"%\" LIMIT 30") {
            cities!.append(row[0] as! String)
        }
        resultsTableView!.reloadData()
    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if cities == nil {
            return 0
        }
        return cities!.count
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell: UITableViewCell = tableView.dequeueReusableCellWithIdentifier("CityCell") as! UITableViewCell
        cell.textLabel?.text = self.cities?[indexPath.row]
        return cell
    }     

}

Upvotes: 3

Related Questions