Created
September 1, 2015 23:58
-
-
Save algal/734294d72399eeaf6bb0 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Swift 1.2 | |
// synchronous JSON download | |
import XCPlayground | |
// my goodness all this complexity is just for an unconditional synchronous | |
// get in a playground on HTTP or HTTPS and decoding to JSON. sad. | |
public func waitUntilTrue(@autoclosure pred:()->Bool, secondsUntilTimeout duration:NSTimeInterval = 25) | |
{ | |
let previousPlayGroundRunStatus = XCPExecutionShouldContinueIndefinitely() | |
XCPSetExecutionShouldContinueIndefinitely(continueIndefinitely: true) | |
let start = NSDate() | |
while true { | |
if pred() { | |
NSLog("condition met.") | |
break | |
} | |
else if fabs(start.timeIntervalSinceNow) > duration { | |
NSLog("timeout") | |
break | |
} | |
else { | |
sleep(1) | |
} | |
} | |
XCPSetExecutionShouldContinueIndefinitely(continueIndefinitely: previousPlayGroundRunStatus) | |
} | |
public class NSURLSessionAllowBadCertificateDelegate : NSObject, NSURLSessionDelegate | |
{ | |
public func URLSession(session: NSURLSession, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential!) -> Void) | |
{ | |
if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust | |
{ | |
let trustObject = challenge.protectionSpace.serverTrust | |
let credential = NSURLCredential(forTrust: challenge.protectionSpace.serverTrust) | |
completionHandler(NSURLSessionAuthChallengeDisposition.UseCredential,credential) | |
} | |
else { | |
completionHandler(NSURLSessionAuthChallengeDisposition.PerformDefaultHandling,nil) | |
} | |
} | |
} | |
public func downloadJSON(URLString:String, orTimeoutAfterDuration duration:NSTimeInterval = 10) -> AnyObject? | |
{ | |
let url = NSURL(string: URLString)! | |
let session = NSURLSession( | |
configuration: NSURLSessionConfiguration.ephemeralSessionConfiguration(), | |
delegate: NSURLSessionAllowBadCertificateDelegate(), | |
delegateQueue: nil) | |
var result:AnyObject? | |
let task = session.dataTaskWithURL(url, completionHandler: { (data, response, error) -> Void in | |
var JSONError:NSError? | |
if let response = response as? NSHTTPURLResponse where response.statusCode == 200, | |
let data = data | |
{ | |
result = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.allZeros, error: &JSONError) | |
} | |
}) | |
task.resume() | |
// just poll every sec. would be better to use an async NSOperation? | |
waitUntilTrue(result != nil, secondsUntilTimeout: duration) | |
return result | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment