Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DispatchGroup.wait() freezes program

I am making two asynchronous network calls and would like to use a Dispatch Group to wait until the call complete and then resume. My program is freezing.

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

And here is one of the network calls:

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

The network calls worked until I introduced Dispatch Group code.

like image 431
Martin Muldoon Avatar asked Sep 26 '26 05:09

Martin Muldoon


1 Answers

I've resolved this.

The problem was that myDispatchGroup.enter() and self.myDispatchGroup.leave() where being called on different threads. I moved the call to the beginning and very end of the network requests and it works fine now.

like image 177
Martin Muldoon Avatar answered Sep 27 '26 20:09

Martin Muldoon