本文介绍了我可以通过Swift中的NSURLSession以某种方式执行同步HTTP请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我可以通过Swift中的 NSURLSession
以某种方式执行同步HTTP请求吗?
Can I somehow do a synchronous HTTP request via NSURLSession
in Swift?
我可以执行异步请求通过以下代码:
I can do an asynchronous request via the following code:
if let url = NSURL(string: "https://2ch.hk/b/threads.json") {
let task = NSURLSession.sharedSession().dataTaskWithURL(url) {
(data, response, error) in
var jsonError: NSError?
let jsonDict = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: &jsonError) as [String: AnyObject]
if jsonError != nil {
return
}
// ...
}
task.resume()
}
但同步请求呢?
提前致谢。
推荐答案
您可以使用此NSURLSession扩展来添加同步方法:
You can use this NSURLSession extension to add a synchronous method:
extension NSURLSession {
func synchronousDataTaskWithURL(url: NSURL) -> (NSData?, NSURLResponse?, NSError?) {
var data: NSData?, response: NSURLResponse?, error: NSError?
let semaphore = dispatch_semaphore_create(0)
dataTaskWithURL(url) {
data = $0; response = $1; error = $2
dispatch_semaphore_signal(semaphore)
}.resume()
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER)
return (data, response, error)
}
}
Swift 3的更新:
extension URLSession {
func synchronousDataTask(with url: URL) -> (Data?, URLResponse?, Error?) {
var data: Data?
var response: URLResponse?
var error: Error?
let semaphore = DispatchSemaphore(value: 0)
let dataTask = self.dataTask(with: url) {
data = $0
response = $1
error = $2
semaphore.signal()
}
dataTask.resume()
_ = semaphore.wait(timeout: .distantFuture)
return (data, response, error)
}
}
这篇关于我可以通过Swift中的NSURLSession以某种方式执行同步HTTP请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!