我正在尝试在此处遵循本指南:https ://elliotekj.com/2019/12/11/sqlite-ios-getting-started-with-grdb虽然有帮助,但它并不完全是一个教程。
到目前为止,我有这个代码:
应用数据库
import GRDB
var dbQueue: DatabaseQueue!
class AppDatabase {
static func setup(for application: UIApplication) throws {
let databaseURL = try FileManager.default
.url(for: .applicationDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
.appendingPathComponent("db.sqlite")
dbQueue = try DatabaseQueue(path: databaseURL.path)
}
}
在我的AppDelegate中,这段代码:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
try! AppDatabase.setup(for: application)
return true
}
它认为以上是正确的。目前,我正在通过 Navicat 操作我的数据库,所以我知道我的表很好。但是现在我需要做什么才能简单地阅读我的表格?
这是我的 SwiftUI ContentView:
import SwiftUI
import GRDB
struct ContentView: View {
@State private var firstName: String = "Saul"
@State private var dateOfBirth: String = "1992-05-12"
var body: some View {
ZStack {
VStack{
HStack {
Text("Name")
Spacer()
TextField(" Enter text ", text: $firstName)
.frame(width: 160, height: 44)
.padding(4)
.border(Color.blue)
}.frame(width:300)
HStack {
Text("Date of Birth")
Spacer()
TextField(" Enter text ", text: $dateOfBirth)
.frame(width: 160, height: 44)
.padding(4)
.border(Color.blue)
}.frame(width:300)
}.foregroundColor(.gray)
.font(.headline)
VStack {
Spacer()
Button(action: {
}) {
Text("Add").font(.headline)
}
.frame(width: 270, height: 64)
.background(Color.secondary).foregroundColor(.white)
.cornerRadius(12)
}
}
}
}
private func readPerson() {
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
struct Person {
var personID: Int64?
var firstName: String
var lastName: String?
var dateOfBirth: String
}
extension Person: Codable, FetchableRecord, MutablePersistableRecord {
// Define database columns from CodingKeys
private enum Columns {
static let personID = Column(CodingKeys.personID)
static let firstName = Column(CodingKeys.firstName)
static let lastName = Column(CodingKeys.lastName)
static let dateOfBirth = Column(CodingKeys.dateOfBirth)
}
// Update a person id after it has been inserted in the database.
mutating func didInsert(with rowID: Int64, for column: String?) {
personID = rowID
}
}
我真的不明白在 readPerson() 中写什么或将它放在我的视图中的什么位置。现在,我很乐意从表中填充我的文本字段,但当然,我想使用按钮添加人员。