Swift:AppDeart中AppStart的网络请求 - ViewController中的CompletionHandler?

时间:2017-01-01 01:04:47

标签: swift asynchronous networking request completionhandler

我的应用程序基于带有4个ViewControllers的TabBarController。它们中的所有4个都依赖于相同的数据。这就是为什么我想在AppDelegate的App start加载数据。

然而,ViewController如何知道请求已完成?例如,如果出现错误(例如没有互联网连接),如何将此错误传递给这4个ViewController中的任何一个以显示警报?

1 个答案:

答案 0 :(得分:0)

使用NotificationCenter实现(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)
        }
    }

}