0
我需要在另一个请求中执行一个HTTP请求,就我所知,这需要同步。
在这种情况下,我获取一系列“帖子”并获取关于它们的信息。
下面的代码,以帮助您了解情况较好:iOS中的另一个请求中的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()
}
的问题是,虽然for
循环运行着的getCommentCountForPostID
功能异步调度。我需要该函数首先发出请求才能完成,然后才能继续执行getPosts()
。我已经尝试了许多与dispatch_sync()
代码包装不同部分的组合,但没有成功。
我该如何做到这一点?非常感谢!
您是否已经尝试过使用dispatch_semaphore helper方法?如果没有,试试看吧 – HorseT
要解决这个问题最好适合NSURLConnection。它使用NSOperations,这很容易解决这个问题(例如使用依赖关系)。 –
@HorseT你能告诉我一个它的用法的例子吗?我查了一下,但不太明白如何使用它在我的情况下 – Eilon