Skip to content

Instantly share code, notes, and snippets.

@collinsrj
Last active August 29, 2015 14:25
Show Gist options
  • Save collinsrj/46ac8b4d302558244aba to your computer and use it in GitHub Desktop.
Save collinsrj/46ac8b4d302558244aba to your computer and use it in GitHub Desktop.
An example in Swift 2 of connecting to an HTTPS service and parsing the resulting JSON.
let urlString = "https://example.com/names"
guard let url = NSURL(string: urlString) else {
fatalError("The URL: \(urlString) wasn't valid!")
}
let request = NSMutableURLRequest(URL: url)
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(request, completionHandler: {(data, response, error) -> Void in
do {
let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableLeaves)
print("JSON is \(json)")
} catch let jsonErr as NSError {
fatalError("A problem happened trying to parse the JSON! \(jsonErr)")
} catch {
fatalError("Not sure what happened here! \(error)")
}
})
task!.resume()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment