内容
✍️ 描述
AsyncViewController
作为特定视图加载数据和展示视图控制器之间的桥梁。在您等待响应时,它将展示一个加载界面,您可以在事先不将这些逻辑全部放入最终视图控制器的情况下,预先提供目的地视图控制器(无论是成功还是错误)。
🖥 示例
旧方法
最初的动机是去除详情视图控制器内的可选对象属性,并从详情视图控制器中移除包括数据加载和显示加载视图在内的逻辑。
想象一个BookViewController
class BookViewController: UIViewController {
var book: Book?
// Having the represented object for this view controller as an optional is inconvenient.
var loadingView: LoadingView?
// Also having the loading view in here is inconvenient since we only need it once in the beginning.
init(bookId: Int) {
super.init(...)
// Load the book here
MyLibrary.loadBook(id: bookId) { result in
// Refresh UI
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Then you initialize your UI, first without data but after loading again with data.
}
}
新方法
AsyncViewController
隐藏了样板代码,并提供了方便的初始化器来定义您的异步调用、成功时的视图控制器以及失败时的解决操作。
想象从BookShelfViewController调用此代码
func presentBookViewController(bookId: Int) {
let asyncViewController = AsyncViewController(load: { callback in
MyLibrary.loadBook(id: bookId, handler: callback)
}, success: { book -> BookViewController in
return BookViewController(book: book)
}) { error -> AsyncViewController<BookViewController, String, Error>.FailureResolution in
return .showViewController(ErrorViewController(error))
}
asyncViewController.overridesNavigationItem = true
present(asyncViewController, animated: true)
}
🎟 演示
您可以在本仓库中找到此演示应用程序。
🔨 定制
错误处理
当加载失败时,您可以提供自定义操作。`FailureResolution`枚举提供了一个您可以使用来传递回调的case。
也许您想关闭视图控制器,或从导航堆栈中弹出。
return .custom({ asyncViewController in
asyncViewController.dismiss(animated: true)
})
自定义加载视图
如果您想展示自己的加载视图,可以使用任何遵循在此处描述的`LoadingAnimatable`协议的`UIViewController`。
asyncViewController.loadingViewController = MyLoadingViewController()
查看演示
💻 如何使用
CocoaPods:
AsyncViewController
可在CocoaPods上找到。只需在您的Podfile
中添加以下行:
pod 'AsyncViewController'
Swift包管理器:
将以下内容添加到您的Package.swift
文件中
dependencies: [
.package(url: "https://github.com/lukaswuerzburger/AsyncViewController.git", from: "2.1.1")
]
⚠️ 要求
- Swift 5+
- iOS 9+
- Xcode 9+
💆 灵感
💪 贡献
欢迎提交问题和拉取请求。