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()
}
But what about synchronous request?
Thanks in advance.
You can use this NSURLSession extension to add a synchronous method:
Update for Swift 3:
Apple thread discussing the same issue.
Updated one of the answers to use a URLRequest instead, so we can use PUT etc instead.
I'm calling like this.
Be careful with synchronous requests because it can result in bad user experience but I know sometimes its necessary. For synchronous requests use NSURLConnection: