Swift: Network-Request at AppStart in AppDelegate - CompletionHandler in ViewController?

451 views Asked by At

my app is based on a TabBarController with 4 ViewControllers. All 4 of them are dependent of the same data. This is why I would like to load the data at the App start in the AppDelegate.

However, how does the ViewController know, that the request is completed? For example, if there is an error (e.g. no internet connection), how do I pass this error to any of these 4 ViewController to present an alert?

1

There are 1 answers

1
bubuxu On

Use NotificationCenter to implement (Swift 3 code):

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)
        }
    }

}