我有以下代码来获取对评论列表的回复.(1条评论有很多回复)
static func fetchCommentsAndTheirReplies(articleId: String, failure: (()->Void)?, success: (comments: [[String: AnyObject]], replies: [[[String: AnyObject]]], userIds: Set)->Void) { var retComments = [[String: AnyObject]]() var retReplies = [[[String: AnyObject]]]() var retUserIds = Set () Alamofire.request(.GET, API.listComment, parameters: [API.articleId: articleId]).responseJSON { response in guard let comments = response.result.value as? [[String: AnyObject]] else { failure?() return } print(comments) retComments = comments let group = dispatch_group_create() for (commentIndex, comment) in comments.enumerate() { guard let id = comment["_id"] as? String else {continue} let relevantUserIds = parseRelaventUserIdsFromEntity(comment) for userId in relevantUserIds { retUserIds.insert(userId) } retReplies.append([[String: AnyObject]]()) dispatch_group_enter(group) Alamofire.request(.GET, API.listReply, parameters: [API.commentId: id]).responseJSON { response in if let replies = response.result.value as? [[String: AnyObject]] { for (_, reply) in replies.enumerate() { let relevantUserIds = parseRelaventUserIdsFromEntity(reply) for userId in relevantUserIds { retUserIds.insert(userId) } } //TODO: need to capture commentIndex? retReplies[commentIndex] = replies } dispatch_group_leave(group) } } dispatch_group_wait(group, DISPATCH_TIME_FOREVER) success(comments: retComments, replies: retReplies, userIds: retUserIds) } }
API.listReply
永远不会调用完整的请求处理程序. dispatch_group_enter(group)
被调用一次,并且从不调用dispatch_group_leave(group).代码陷入困境dispatch_group_wait
.奇怪的是,即使UI被卡住了,这也很奇怪,因为整个函数都是异步的.