Skip to content

Instantly share code, notes, and snippets.

@algal
Last active April 18, 2016 17:30
Show Gist options
  • Save algal/dec51703016b446a46f0bcbab5b8b2b9 to your computer and use it in GitHub Desktop.
Save algal/dec51703016b446a46f0bcbab5b8b2b9 to your computer and use it in GitHub Desktop.
NSURLSession extension to add synchronous data task request.
import Foundation
/**
NSURLSession extension to add synchronous data task request, throwing on
timeout.
Using a GCD semaphore internally.
Deeper wisdom from Quinn the Eskimo on why you may not want this:
<https://forums.developer.apple.com/thread/11519>
*/
enum SynchronousRequest : ErrorType { case Timeout }
extension NSURLSession {
func sendSynchronousRequest(request:NSURLRequest) -> (NSData?,NSURLResponse?,NSError?)
{
let sem = dispatch_semaphore_create(0)
var result:(NSData?,NSURLResponse?,NSError?)
let task = self.dataTaskWithRequest(request) { (theData, theResponse, theError) in
result = (theData,theResponse,theError)
dispatch_semaphore_signal(sem)
}
task.resume()
dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER)
return result
}
func sendSynchronousRequest(request:NSURLRequest,timeout:NSTimeInterval) throws -> (NSData?,NSURLResponse?,NSError?)
{
let sem = dispatch_semaphore_create(0)
var result:(NSData?,NSURLResponse?,NSError?)
let task = self.dataTaskWithRequest(request) { (theData, theResponse, theError) in
result = (theData,theResponse,theError)
dispatch_semaphore_signal(sem)
}
task.resume()
let t = dispatch_time(DISPATCH_TIME_NOW, Int64(NSEC_PER_SEC) * Int64(timeout))
let noTimeout = dispatch_semaphore_wait(sem, t)
if noTimeout != 0 {
throw SynchronousRequest.Timeout
}
return result
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment