I have this code from here to do synchronous request of a URL on Swift 2.
func send(url: String, f: (String)-> ()) {
var request = NSURLRequest(URL: NSURL(string: url)!)
var response: NSURLResponse?
var error: NSErrorPointer = nil
var data = NSURLConnection.sendSynchronousRequest(request, returningResponse: &response, error: error)
var reply = NSString(data: data, encoding: NSUTF8StringEncoding)
f(reply)
}
but the function NSURLConnection.sendSynchronousRequest(request, returningResponse: &response, error: error)
was deprecated and I don't see how one can do synchronous requests on Swift, cause the alternative is asynchronous. Apparently Apple deprecated the only function that can do it synchronously.
How can I do that?
Synchronous requests are sometimes fine on background threads. Sometimes you have a complicated, impossible to change code base full of async requests, etc. Then there is a small request that can't be folded into the current system as async. If the sync fails, then you get no data. Simple. It mimics how the file system works.
Sure it does not cover all sorts of eventualities, but there are lots of eventualities not covered in async as well.
If you really wanna do it synchronously you can always use a semaphore:
EDIT: Add some hackish ! so the code works, don't do this in production code
Swift 3.0+ (3.0, 3.1, 3.2, 4.0)
There is a reason behind deprecation - there is just no use for it. You should avoid synchronous network requests as a plague. It has two main problems and only one advantage (it is easy to use.. but isn't async as well?):
Instead of this, just use asynchronous request:
iOS9 Deprecation
Since in iOS9 this method is being deprecated, I suggest you to use NSURLSession instead:
Based on @fpg1503 answer I made a simple extension in Swift 3:
Then you simply call: