2017-01-01 7 views
0

私のアプリは4つのViewControllerを持つTabBarControllerに基づいています。 4人すべてが同じデータに依存しています。これがAppDelegateのApp開始時にデータをロードする理由です。Swift:AppDelegateのAppStartでネットワークリクエスト - ViewControllerのCompletionHandler?

しかし、ViewControllerは、要求が完了したことをどのように知っていますか?たとえば、インターネットに接続していないなどのエラーが発生した場合、どのようにこれらの4つのViewControllerにこのエラーを渡してアラートを表示しますか? (スウィフト3コード)を実装する

+0

使用NSNotificatioCenterあなたのデータの準備ができているときがある場合、(例えば「ErrorOccurs」と呼ばれる)別の通知を(「DataIsReady」と呼ばれる)の通知を投稿しますエラーが発生すると、すべてのView Controllerが通知を監視して処理します。 – bubuxu

答えて

0

利用通知センター:

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に保存して、ポストコールに渡す必要はありません(ハンドラではobjは空になりますが、シングルトンクラスからアクセスできます) ) – bubuxu

関連する問題