我需要在另一个请求中执行HTTP请求,据我所知,这需要同步 在这种情况下,我获取一系列“帖子”并获取有关它们的信息 这是代码,以帮助您更好地了解情况:
// getPosts()
...
let task = NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: { (data: NSData!, response: NSURLResponse?, error: NSError?) -> Void in
if response != nil {
let dataDictionary = NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers, error: &err) as [NSDictionary]
for postDic: NSDictionary in dataDictionary {
let post = Post(postId: postDic["post_id"] as String)
post.likes = postDic["likes"] as String
post.views = postDic["views"] as String
self.getCommentCountForPostID(post.postId, completion: { (count) -> Void in
post.comments = count
})
...
self.posts.addObject(post)
}
// reloading table view etc
}
})
task.resume()
这是函数getCommentCountForPostID
:
func getCommentCountForPostID(postID: String, completion: ((count : String?) -> ())) {
...
let task = NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: { (data: NSData!, response: NSURLResponse?, error: NSError?) -> Void in
if response != nil {
let resultCount: NSString! = NSString(bytes: data.bytes, length: data.length, encoding: NSASCIIStringEncoding)
print(resultCount)
completion(count: resultCount)
}
})
task.resume()
}
问题是getCommentCountForPostID
函数在for
循环向前运行时异步调度。我需要该函数首先评论请求完成,然后继续执行getPosts()
。我尝试了许多使用dispatch_sync()
在代码中包装不同部分的组合,但没有成功
我怎样才能做到这一点?非常感谢!
答案 0 :(得分:0)
为您的目的使用递归。
加载第一篇文章 - >处理它 - >加载下一个 - >加载所有帖子后完成。
我创建了一个名为'loopAndLoad'的辅助方法,它将您的数据数组作为参数,并处理当前项的索引
let task = NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: { (data: NSData!, response: NSURLResponse?, error: NSError?) -> Void in
if response != nil {
let dataDictionary = NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers, error: &err) as [NSDictionary]
self.loopAndLoad(0, dataDictionary);
}
})
task.resume()
func loopAndLoad( index: Int, dataArray: Array<NSDictionary>)
{
let postDic = dataArray[index]
let post = Post(postId: postDic["post_id"] as String)
post.likes = postDic["likes"] as String
post.views = postDic["views"] as String
self.getCommentCountForPostID(post.postId, completion: { (count) -> Void in
post.comments = count
self.posts.addObject(post)
if (++index < dataArray.count)
{
self.loopAndLoad(index, dataArray)
}
else
{
/// end of loop
}
})
}
func getCommentCountForPostID(postID: String, completion: ((count : String?) -> ())) {
...
let task = NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: { (data: NSData!, response: NSURLResponse?, error: NSError?) -> Void in
if response != nil {
let resultCount: NSString! = NSString(bytes: data.bytes, length: data.length, encoding: NSASCIIStringEncoding)
print(resultCount)
completion(count: resultCount)
}
})
task.resume()
}