Ich mache zwei asynchrone Netzwerkanrufe und möchte eine Dispatch-Gruppe verwenden, um zu warten, bis der Anruf beendet und dann fortgesetzt wird. Mein Programm friert ein.DispatchGroup.wait() friert das Programm ein
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)
}
}
Und hier ist eine der Netzwerk-Anrufe:
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()
}
}
}
Die Netzwerk-Anrufe bearbeitet, bis ich Dispatch-Gruppencode eingeführt.
Warum verwenden Sie 'wait()' anstelle des Hinzufügens eines Blocks zu 'notify()', der ausgeführt wird, wenn alle Aufgaben in der Versandgruppe abgeschlossen sind? – Abizern
Ich habe dies nur zu notify() geändert. Viel besserer Ansatz. Vielen Dank!! –