Skip to content

Instantly share code, notes, and snippets.

@cmoulton
Last active January 25, 2024 13:56
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save cmoulton/b6c3a8e6cc1e4d31abd0ea0bdc01039d to your computer and use it in GitHub Desktop.
Save cmoulton/b6c3a8e6cc1e4d31abd0ea0bdc01039d to your computer and use it in GitHub Desktop.
Simple Alamofire Calls in Swift 3.0.1
func alamofireGet() {
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")
print("Error: \(response.result.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 alamofirePost() {
let todosEndpoint: String = "https://jsonplaceholder.typicode.com/todos"
let newTodo: [String: Any] = ["title": "My First Post", "completed": 0, "userId": 1]
Alamofire.request(todosEndpoint, method: .post, parameters: newTodo, encoding: JSONEncoding.default)
.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")
print("Error: \(response.result.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 alamofireDelete() {
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")
print(response.result.error!)
return
}
print("DELETE ok")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment