Swift:AppDelegate中的AppStart中的Network-Request - ViewController中的CompletionHandler?
问题描述:
我的应用程序基于带有4个ViewControllers的TabBarController。所有4个都依赖于相同的数据。这就是为什么我想要在AppDelegate的App start中加载数据的原因。Swift:AppDelegate中的AppStart中的Network-Request - ViewController中的CompletionHandler?
但是,ViewController如何知道请求已完成?例如,如果发生错误(例如没有互联网连接),我如何将这个错误传递给这4个ViewController中的任何一个来显示警报?
答
使用通知中心来实现(SWIFT 3码):
extension Notification.Name {
static var RequestCompleted = Notification.Name(rawValue: "MyRequestIsCompleted")
static var RequestError = Notification.Name(rawValue: "MyRequestError")
}
class DataRequest {
func request() {
// if there is error:
let error = NSError(domain: "Error Sample", code: 0, userInfo: nil)
NotificationCenter.default.post(name: .RequestError, object: error)
// if the request is completed
let data = "your data is here"
NotificationCenter.default.post(name: .RequestCompleted, object: data)
}
}
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(requestCompleted(_:)), name: .RequestCompleted, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(requestError(_:)), name: .RequestError, object: nil)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
func requestCompleted(_ notification: Notification) {
if let obj = notification.object {
print(obj)
}
}
func requestError(_ notification: Notification) {
if let obj = notification.object {
print(obj)
}
}
}
+0
如果你的DataRequest类是一个单例对象,你可以将请求数据保存到一个iVar中,并且不需要传递给post调用(所以在处理程序中,obj将是空的,但是你可以从singleton类访问它) – bubuxu
使用NSNotificatioCenter张贴的通知(称为“DataIsReady”)当你的数据准备好,另一个通知(例如所谓的“ErrorOccurs”)时,有错误,所有视图控制器观察通知并处理它们。 – bubuxu