Last active
December 8, 2020 09:29
-
-
Save cmoulton/9591be2b10043e6811a845f6dcbe821a to your computer and use it in GitHub Desktop.
Simple Alamofire Calls in Swift 4
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 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
Swift 5 and Alamofire 5 version: