Create a gist now

Instantly share code, notes, and snippets.

Embed
import Foundation
/// NSURLSession synchronous behavior
/// Particularly for playground sessions that need to run sequentially
public extension NSURLSession {
/// Return data from synchronous URL request
public static func requestSynchronousData(request: NSURLRequest) -> NSData? {
var data: NSData? = nil
let semaphore: dispatch_semaphore_t = dispatch_semaphore_create(0)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: {
taskData, _, error -> () in
data = taskData
if data == nil, let error = error {print(error)}
dispatch_semaphore_signal(semaphore);
})
task.resume()
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER)
return data
}
/// Return data synchronous from specified endpoint
public static func requestSynchronousDataWithURLString(requestString: String) -> NSData? {
guard let url = NSURL(string:requestString) else {return nil}
let request = NSURLRequest(URL: url)
return NSURLSession.requestSynchronousData(request)
}
/// Return JSON synchronous from URL request
public static func requestSynchronousJSON(request: NSURLRequest) -> AnyObject? {
guard let data = NSURLSession.requestSynchronousData(request) else {return nil}
return try? NSJSONSerialization.JSONObjectWithData(data, options: [])
}
/// Return JSON synchronous from specified endpoint
public static func requestSynchronousJSONWithURLString(requestString: String) -> AnyObject? {
guard let url = NSURL(string: requestString) else {return nil}
let request = NSMutableURLRequest(URL:url)
request.HTTPMethod = "GET"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
return NSURLSession.requestSynchronousJSON(request)
}
}
@tkoak

This comment has been minimized.

Show comment
Hide comment
@tkoak

tkoak Jan 21, 2016

Very useful!

tkoak commented Jan 21, 2016

Very useful!

@xinchrome

This comment has been minimized.

Show comment
Hide comment
@xinchrome

xinchrome Apr 2, 2016

thanks, i will convert these into objc

thanks, i will convert these into objc

@mbxymail

This comment has been minimized.

Show comment
Hide comment
@mbxymail

mbxymail Sep 20, 2016

Awesome save me a lot of time!!!!!!!!

Awesome save me a lot of time!!!!!!!!

@almatri

This comment has been minimized.

Show comment
Hide comment
@almatri

almatri Nov 11, 2016

Great, works well

almatri commented Nov 11, 2016

Great, works well

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment