Skip to content

Instantly share code, notes, and snippets.

@cmoulton
Last active November 4, 2022 00:29
Show Gist options
  • Save cmoulton/149b03b5ea2f4c870a44526a02618a30 to your computer and use it in GitHub Desktop.
Save cmoulton/149b03b5ea2f4c870a44526a02618a30 to your computer and use it in GitHub Desktop.
URLSession Calls in Swift 3.0.1
func makeGetCall() {
// Set up the URL request
let todoEndpoint: String = "https://jsonplaceholder.typicode.com/todos/1"
guard let url = URL(string: todoEndpoint) else {
print("Error: cannot create URL")
return
}
let urlRequest = URLRequest(url: url)
// set up the session
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config)
// make the request
let task = session.dataTask(with: urlRequest) {
(data, response, error) in
// check for any errors
guard error == nil else {
print("error calling GET on /todos/1")
print(error)
return
}
// make sure we got data
guard let responseData = data else {
print("Error: did not receive data")
return
}
// parse the result as JSON, since that's what the API provides
do {
guard let todo = try JSONSerialization.jsonObject(with: responseData, options: []) as? [String: AnyObject] else {
print("error trying to convert data to JSON")
return
}
// now we have the todo, let's just print it to prove we can access it
print("The todo is: " + todo.description)
// the todo object is a dictionary
// so we just access the title using the "title" key
// so check for a title and print it if we have one
guard let todoTitle = todo["title"] as? String else {
print("Could not get todo title from JSON")
return
}
print("The title is: " + todoTitle)
} catch {
print("error trying to convert data to JSON")
return
}
}
task.resume()
}
Copy link

ghost commented Mar 17, 2017

Same. No output.

@gregoriomelo
Copy link

If you're running in Playground, you might need to import PlaygroundSupport (assuming you're on Swift 3):

import PlaygroundSupport

and, at the end of your file add the following:

PlaygroundPage.current.needsIndefiniteExecution = true

@lkennon
Copy link

lkennon commented Feb 15, 2020

No output either. Not in Playground but Swift project (Xcode 9.4.1)

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