Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brandonvanha/39bbefa8cd1d4d3006069e1a1a1069ab to your computer and use it in GitHub Desktop.
Save brandonvanha/39bbefa8cd1d4d3006069e1a1a1069ab to your computer and use it in GitHub Desktop.
Simple Alamofire Calls in Swift 4
import Alamofire
func makeGetCallWithAlamofire() {
let todoEndpoint: String = "https://jsonplaceholder.typicode.com/todos/1"
Alamofire.request(todoEndpoint)
.responseJSON { response in
// check for errors
guard response.result.error == nil else {
// got an error in getting the data, need to handle it
print("error calling GET on /todos/1")
print(response.result.error!)
return
}
// make sure we got some JSON since that's what we expect
guard let json = response.result.value as? [String: Any] else {
print("didn't get todo object as JSON from API")
if let error = response.result.error {
print("Error: \(error)")
}
return
}
// get and print the title
guard let todoTitle = json["title"] as? String else {
print("Could not get todo title from JSON")
return
}
print("The title is: " + todoTitle)
}
}
func makePostCallWithAlamofire() {
let newTodo: [String: Any] = ["title": "My First Post", "completed": 0, "userId": 1]
Alamofire.request(TodoRouter.create(newTodo))
.responseJSON { response in
guard response.result.error == nil else {
// got an error in getting the data, need to handle it
print("error calling POST on /todos/1")
print(response.result.error!)
return
}
// make sure we got some JSON since that's what we expect
guard let json = response.result.value as? [String: Any] else {
print("didn't get todo object as JSON from API")
if let error = response.result.error {
print("Error: \(error)")
}
return
}
// get and print the title
guard let idNumber = json["id"] as? Int else {
print("Could not get id number from JSON")
return
}
print("Created todo with id: \(idNumber)")
}
}
func makeDeleteCallWithAlamofire() {
let firstTodoEndpoint: String = "https://jsonplaceholder.typicode.com/todos/1"
Alamofire.request(firstTodoEndpoint, method: .delete)
.responseJSON { response in
guard response.result.error == nil else {
// got an error in getting the data, need to handle it
print("error calling DELETE on /todos/1")
if let error = response.result.error {
print("Error: \(error)")
}
return
}
print("DELETE ok")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment