DispatchGroup.wait()冻结程序

时间:2017-08-17 13:20:49

标签: ios swift3 grand-central-dispatch

我正在进行两次异步网络呼叫,并希望使用Dispatch Group等待呼叫完成然后恢复。我的节目很冷。

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

在我介绍Dispatch Group代码之前,网络调用一直有效。

1 个答案:

答案 0 :(得分:3)

我已经解决了这个问题。

问题是myDispatchGroup.enter()self.myDispatchGroup.leave()在不同的线程上被调用。我将呼叫移动到网络请求的开头和结尾,现在工作正常。