Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Swift:ViewController中AppDelegate-CompletionHandler中AppStart处的网络请求?_Swift_Asynchronous_Networking_Request_Completionhandler - Fatal编程技术网

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

Swift:ViewController中AppDelegate-CompletionHandler中AppStart处的网络请求?,swift,asynchronous,networking,request,completionhandler,Swift,Asynchronous,Networking,Request,Completionhandler,我的应用程序基于带有4个ViewController的TabBarController。所有4个都依赖于相同的数据。这就是为什么我想在AppDelegate中的应用程序开始时加载数据 但是,ViewController如何知道请求已完成?例如,如果出现错误(例如,没有internet连接),如何将此错误传递给这4个ViewController中的任何一个以显示警报?使用NotificationCenter实现(Swift 3代码): 当数据准备就绪时,使用NSNotificatioCenter发

我的应用程序基于带有4个ViewController的TabBarController。所有4个都依赖于相同的数据。这就是为什么我想在AppDelegate中的应用程序开始时加载数据


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

使用NotificationCenter实现(Swift 3代码):


当数据准备就绪时,使用NSNotificatioCenter发布通知(称为“DataIsReady”),当出现错误时,所有视图控制器都会观察并处理通知。如果DataRequest类是singleton对象,您可以将请求数据保存到iVar,而不需要传递到post调用(因此在处理程序中,obj将为空,但您可以从singleton类访问它)
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)
        }
    }

}