2017-03-27 1 views
0

私はAlamofireリクエストを関数の一部として持っており、残りの関数が実行される前に完了するようにリクエストが必要です。あなたは以下の完全な機能を見ることができます。Alamofireリクエストが完了するのを待つ必要があります - スウィフト

@IBAction func btnScanPressed(_ sender: Any) { 

    // Retrieve the QRCode content 
    // By using the delegate pattern 
    readerVC.delegate = self 

    readerVC.completionBlock = { (result: QRCodeReaderResult?) in 
     print(result?.value) 

    Alamofire.request((result?.value)!).responseString { response in 
     debugPrint(response) 

     if let json = response.result.value { 

      let returnedJSON = JSON.init(parseJSON: json); 


      //TESTED -> this section does work and does update the values 

      self.co.setVideoURL(url: (returnedJSON["VideoURL"].string)!) 

      self.co.setDisplayText(text: returnedJSON["DisplayText"].string!) 

      self.co.setHasUpdated(value: true) 


      print("VARIABLES NOW SET") 


     } 


    } 

    } 



    // Presents the readerVC as modal form sheet (This needs to happen AFTER the Alamofire has completed) 
    readerVC.modalPresentationStyle = .formSheet 

    present(readerVC, animated: true, completion: nil) 

} 

回答を解析してオブジェクトに値を割り当てるためにswiftyJSONを使用しています。関数全体が完了する前にAlamofireリクエストを完了する必要があります。どんな提案も大歓迎です!

+0

モーダルのプレゼンテーションコードをネットワーク要求完了ブロックに移動するだけでいいですか(また、おそらくメインスレッド上で実行されるようにする必要があります)。完了ブロック内のコードは、要求が完了した後に発生します。 –

答えて

0

基本的に、Alamofireリクエストの後にコードをリクエストクロージャに移動する必要があります。要求クロージャー内のコードは、要求が正常に完了した後、または失敗した後にのみ発生します(サーバーエラー、タイムアウトなど)。次のコードが役に立ちます。

@IBAction func btnScanPressed(_ sender: Any) { 
// Retrieve the QRCode content 
// By using the delegate pattern 
readerVC.delegate = self 

readerVC.completionBlock = { (result: QRCodeReaderResult?) in 
    print(result?.value) 

Alamofire.request((result?.value)!).responseString { response in 
    debugPrint(response) 

    if let json = response.result.value { 

     let returnedJSON = JSON.init(parseJSON: json); 


     //TESTED -> this section does work and does update the values 

     self.co.setVideoURL(url: (returnedJSON["VideoURL"].string)!) 

     self.co.setDisplayText(text: returnedJSON["DisplayText"].string!) 

     self.co.setHasUpdated(value: true) 


     print("VARIABLES NOW SET") 


     // Presents the readerVC as modal form sheet (This needs to happen AFTER the Alamofire has completed) 
     self.readerVC.modalPresentationStyle = .formSheet 

     self.present(readerVC, animated: true, completion: nil) 

    } 


} 

} 



} 
+0

ありがとうございます!これは私のために働いた。私はそれが明らかな何かを知っていた、私はちょうど私の前に解決策を見るにはあまりにもそれを見ていたと思う。乾杯! –

0

なぜあなたはアラモ火ブロックでこれらの最後の2行を入れませんか?

関連する問題