当我的 iOS 应用程序启动时,我想使用SQLite.swift连接到本地 SQLite 数据库,然后向用户显示存储在数据库中的项目列表。建立数据库连接即可throw
。如果连接失败,那么我想向用户显示一个很好的错误消息。
在Main.storyboard
中,我的根视图控制器是UINavigationController
. 导航控制器的根/顶视图控制器是一个UIViewController
包含UITableView
用于显示数据库中项目的一个。
我的第一个想法是连接到AppDelegate
's中的数据库application(_:didFinishLaunchingWithOptions:)
并以某种方式UIAlertController
在UIViewController
. 我似乎无法UIViewController
让UIAlertController
. 即使可以,我也开始怀疑这种方法,因为如果无法从数据库中加载项目,那么表格将无法在警报下呈现。我正在努力的是这样的:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
do {
let documentsDirectories = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
let documentsDirectory = documentsDirectories.first!
let dbPath = documentsDirectory.appendingPathComponent("db.sqlite3")
let db = try Connection("\(dbPath)")
// ...
}
catch {
let navController = window!.rootViewController as! UINavigationController
let itemsController = navController.topViewController as! ItemsController
let failureAlert = UIAlertController(
title: "Fatal Error",
message: "Could not connect to the database.",
preferredStyle: .alert)
itemsController.present(failureAlert, animated: true, completion: nil)
}
//...
}
我的第二个想法仍然是连接到AppDelegate
's中的数据库application(_:didFinishLaunchingWithOptions:)
。如果抛出,则将窗口的根视图更改为用户将看到的错误视图。这样,显示项目的表格甚至永远不会尝试显示项目。
我的第三个想法是变得AppDelegate
更加懒惰并将问题解决。只需创建一个知道 SQLite 数据库文件路径的数据访问对象。将 dao 传递给UIViewController
充当UITableView
. throw
当数据源第一次需要来自数据库的信息时,让 dao 尝试连接(并在必要时迁移数据库模式等)并在那时让它连接。即使 dao 已经连接到数据库,也可能需要为访问数据做好UITableView
准备。throw
您可以分享任何优雅处理此问题的经验吗?
谢谢!