i'm fairly new to programming. I am working with Xcode 6 and swift to build an iOS 8 app. my app has quite lot of data which i have organised into sqlite3 files using the firefox add on. i have dropped these files into my project folder. their extension is .sql now i need to access that data in my app. i have already linked the sqlite3 library by adding libsqlite3.dylib in the build phases tab. now i want to write the code to access the database. i have found a lot of information online with code and examples from iOS 7 and earlier using objective-c but nothing with iOS 8 and swift. if anybody can help me or lead me in the right direction i would be grateful. thanks.
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
you can use sqlite.swift framework to implement database connection with swift here is link https://github.com/stephencelis/SQLite.swift/blob/master/Documentation/Index.md
Here is example to connect sqlite database
var db : Database!
var cat = Expression<String>("ZCATEGORY")
var name = Expression<String>("ZNAME")
var user : Query!
var stmt : Query!
var data : Array<Row>!
@IBOutlet var tabe: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
createdb()
}
internal func createdb()
{
// bundle database within your app
let path = NSBundle.mainBundle().pathForResource("db", ofType: "sqlite")
println(path)
db = Database(path, readonly: true)
// ZFOOD is table name
user = db["ZFOOD"]
println(db)
// select distinct(cat) from ZFOOD
stmt = user.select(distinct : cat)
// Stored query result in array
data = Array(stmt)
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: AnyObject = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)
cell.textLabel.text = data[indexPath.row][cat]
return cell as UITableViewCell
}
I hope this helpful for you