2016-12-13 9 views
1

私はサーバーからいくつかのjsonデータをロードするUIViewControllerを持っています。サーバーがダウンしている場合、またはユーザーがデータをオフにしている場合、ユーザーにその旨を知らせる警告が表示されます。これは、UIAlertControllerを使用して行われます。これは素晴らしいです。したがって、データを必要とするすべてのUIViewControllerによって使用されるため、これを拡張機能に追加しました。今UIAlertControllerはアクションだけでなく拡張機能からのUIViewControllerの呼び出し関数

アラートコードユーザーは、私は警告を上げたのUIViewController内の関数を呼び出したいリトライボタンをタップ

extension UIViewController {  
func connectionLost(){ 
    var message = "Your device has lost connection to the server. Check that you have a valid internet connection and then retry." 

    let alertController = UIAlertController(title: "Connection Lost", 
              message: message, 
              preferredStyle: .alert) 
    let retryAction = UIAlertAction(title:"Retry", style: .default, handler: { 
     action in 

     //call function in the viewcontroller that raised this alert to reload the data 
    }) 
    alertController.addAction(retryAction) 
    self.present(alertController, animated: true, completion: nil) 
} 
} 

設定しています。

私はエクステンションにデリゲートを作成しようとしましたが、クラスのように有線にするのに苦労しました。どのようなアプローチが、アラートを発生させたViewController内の拡張機能から関数を呼び出すのですか?

答えて

1

BaseViewControllerを作成し、Inheritanceを使用する必要があります。これは他の実装にも役立ちます。

​​3210
+0

また、簡単に 'UIAlertAction'レスポンスを処理するためにcompletionHandlerを使うことができます。 –

+0

もちろん、これは実装が簡単なソリューションです。しかし、継承はコードをより集中化します。 「共通の」リトライアクションが必要な場合、または各コントローラが独自の実装を必要とするかどうかによって異なります – lubilis

+0

@lubilisこれは本当にうまく機能し、言及したように私は他の領域でも使用できます。本当にありがとう。 –

0

希望します。

class MyVC: UIViewController { 

    func retry() { 

    } 

    func checkConnection() { 
     connectionLost { (retry) -> (Void) in 
      if retry { 
       self.retry() 
      } 
     } 
    } 
} 


extension UIViewController { 
    func connectionLost(completion: @escaping (_ retry: Bool) -> (Void)) { 
     let message = "Your device has lost connection to the server. Check that you have a valid internet connection and then retry." 

     let alertController = UIAlertController(title: "Connection Lost", 
              message: message, 
              preferredStyle: .alert) 
     let retryAction = UIAlertAction(title:"Retry", style: .default, handler: { 
     action in 
      completion(true)//may be 'false', you decide 
     }) 
     alertController.addAction(retryAction) 
     self.present(alertController, animated: true, completion: nil) 
    } 
} 
+0

ありがとう、しかし私は上のものと一緒に行った:) –

関連する問題