Created
May 7, 2016 13:14
-
-
Save collinsrj/b47980c38be284e956381dfd5b8b430e to your computer and use it in GitHub Desktop.
Synchronous HTTPS Request in Playground
This file contains 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
import Foundation | |
func getEncoding(response: NSHTTPURLResponse) -> NSStringEncoding { | |
guard let encodingName = response.textEncodingName else { | |
return NSUTF8StringEncoding | |
} | |
let encoding = CFStringConvertEncodingToNSStringEncoding(CFStringConvertIANACharSetNameToEncoding(encodingName)) | |
if encoding != UInt(kCFStringEncodingInvalidId) { | |
return encoding | |
} | |
return NSUTF8StringEncoding | |
} | |
let semaphore = dispatch_semaphore_create(0); | |
let session = NSURLSession.sharedSession() | |
let task = session.dataTaskWithURL(NSURL(string: "https://www.google.ie/")!) { (data, response, error) in | |
defer { | |
dispatch_semaphore_signal(semaphore); | |
} | |
guard let httpResponse = response as? NSHTTPURLResponse, receivedData = data where error == nil else { | |
print("error: not a valid http response") | |
return | |
} | |
switch (httpResponse.statusCode) { | |
case 200: | |
let encoding = getEncoding(httpResponse) | |
var first = String(data: receivedData, encoding: encoding) | |
default: | |
print("Unexpected response: \(httpResponse.statusCode)") | |
} | |
} | |
task.resume() | |
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment