zl程序教程

您现在的位置是:首页 >  数据库

当前栏目

[快速学会Swift第三方库] SQLite.swift篇

SQLite 快速 swift 学会 第三方
2023-09-14 09:04:37 时间

推荐使用CocoaPods进行导入,CocoaPods是一个负责管理iOS项目中第三方开源库的工具,安装CocoaPods之后使用命令行就能轻松地对所有第三方开源库进行安装和更新,而不需要每次上GitHub去下载。
CocoaPods的安装过程传送门:iOS 9 导入类库全面详尽过程(Ruby安装- CocoaPods安装- 导入类库)
手动下载:GitHub-SQLite.swift主页

装好CocoaPods后,修改Podfile文件内容为如下:

source https://github.com/CocoaPods/Specs.git

platform :ios, 9.0

use_frameworks!

pod SQLite.swift, ~ 0.10.1

xcodeproj Desktop/Web/Web.xcodeproj

target后面为工程名,最后一行为工程路径(这里的Web是我的工程名)

再执行命令:

$ pod install

在Target- 工程名- Build Settings- Search Paths- User Header Search Paths处添加SQLite.swift所在的目录:

这里写图片描述

选择Target- 工程名- Build Phases,在Link Binary With Libraries中添加 libsqlite3.tbd
在工程的bridging header中加入以下代码:


let path = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0]

let db = try? Connection("\(path)/db.sqlite3")

try! db?.run(users.create(ifNotExists: true, block: { (table) in table.column(id, primaryKey: true) table.column(name) table.column(email, unique: true) }))

等价于执行SQL语句:


let insert = users.insert(name - "究极死胖兽", email - "scuxiatian@foxmail.com")

let rowid = (try! db?.run(insert))!

let insert2 = users.insert(name - "Amazing7", email - "360898864@qq.com")

let rowid2 = (try! db?.run(insert2))!

等价于执行SQL语句:


insert into users (name,email) values(究极死胖兽,scuxiatian@foxmail.com)

insert into users (name,email) values(Amazing7,360898864@qq.com)

for user in (try! db?.prepare(users))! {

 print("Query:id: \(user[id]), name: \(user[name]), email: \(user[email])")

 }

等价于执行SQL语句:


Query:id: 1, name: Optional("究极死胖兽"), email: scuxiatian@foxmail.com

Query:id: 2, name: Optional("Amazing7"), email: 360898864@qq.com

条件查询会在后面用到


let update = users.filter(id == rowid)

try! db?.run(update.update(email - email.replace("foxmail", with: "qq")))

for user in (try! db?.prepare(users.filter(name == "究极死胖兽")))! {

 print("Update:id: \(user[id]), name: \(user[name]), email: \(user[email])")

}

等价于执行SQL语句:


update users set email=replace(email,foxmail,qq) where id == 1

SELECT * FROM users where name=究极死胖兽

执行结果:


try! db?.run(users.filter(id == rowid2).delete())

for user in (try! db?.prepare(users))! {

 print("Delete:id: \(user[id]), name: \(user[name]), email: \(user[email])")

}

等价于执行SQL语句:


这里只列出了数据库的创建和最基本的增删改查操作,如果你希望能够更加深入地学习SQLite.swift,可以前往GitHub-SQLite.swift主页


Eureka可以帮你简单优雅的实现动态table-view表单。它由rows,sections和forms组成。如果你的app包含大量表单,Eureka可以真正帮你节省时间。
Kingfisher是一个轻量的下载和缓存网络图片库。下载和缓存是异步进行操作,已经下载好的图片会缓存在内存和本地,极大得提高app的体验。
通常网络请求返回的是JSON数据,使用ObjectMapper可以让JSON数据直接转化为对象,而使用Alamofire进行网络请求时,使用AlamofireObjectMapper可以直接返回对象,更加简洁。 Alamofire的使用:[快速学会Swift第三方库] Alamofire篇
Cartography 是用来声明 Swift 中的 Auto Layout,无需输入任何 stringly 就可设置自己 Auto Layout 的约束声明。
SwiftyJSON使得用Swift处理JSON数据更加容易。这是解析JSON字符串封装类。实现功能与Javascript中的JSON.parse相近,使用方便。
Alamofire是 Swift 语言的 HTTP 网络开发工具包,AFNetworking的 Swift 版,使用起来相当简单。