2017-08-17 5 views
0

私は2つの非同期ネットワークコールを作成しており、ディスパッチグループを使用してコールが完了してから再開するまで待機したいと考えています。私のプログラムはフリーズしています。DispatchGroup.wait()フリーズプログラム

class CommentRatingViewController: UIViewController, UITextViewDelegate { 
let myDispatchGroup = DispatchGroup() 

@IBAction func saveRatingComment(_ sender: Any) { 
     rating = ratingView.rating 
     if rating != 0.0 { 
      myDispatchGroup.enter() 
      saveRating(articleID: post.articleID, userID: post.userID) //Network call 
      self.updatedRating = true 
     } 
     if commentsTextView.text != "" { 
      myDispatchGroup.enter() 
      saveComment(articleID: post.articleID, userID: post.userID, comment: commentsTextView.text!) //Network call    self.addedComment = true 
     } 
     myDispatchGroup.wait() 
     DispatchQueue.main.async { 
      self.delegate?.didCommentOrRatePost(updatedRating: self.updatedRating, addedComment: self.addedComment) 
     } 
    } 

そして、ここでネットワーク呼び出しのいずれかです。私は派遣グループコードを導入するまで

func saveRating (articleID: String, userID: String) { 

      let userPostURLRaw = "http://www.smarttapp.com/DesktopModules/DnnSharp/DnnApiEndpoint/Api.ashx?method=UpdatePostRating" 
      Alamofire.request(
       userPostURLRaw, 
       method: .post, 
       parameters: ["articleID": articleID, 
          "newRating": self.rating, 
          "UserID": userID] 
      ) 
       .responseString { response in 
        guard let myString = response.result.value else { return } 

       DispatchQueue.main.async { 
        self.myDispatchGroup.leave() 
       } 
      } 
    } 

ネットワーク呼び出しが働いていました。

+1

なぜディスパッチグループ内のすべてのタスクが完了したときに 'notify()'にブロックを追加する代わりに 'wait()'を使用していますか? – Abizern

+0

これをnotify()に変更しました。はるかに良いアプローチ。ありがとう!! –

答えて

0

私はこれを解決しました。

問題はmyDispatchGroup.enter()self.myDispatchGroup.leave()で、異なるスレッドで呼び出されていました。私は、ネットワーク要求の最初と最後まで呼び出しを移しました。今は正常に動作します。