Last active
September 9, 2021 21:01
-
-
Save cmoulton/01fdd4fe2c2e9c8195e1 to your computer and use it in GitHub Desktop.
Quick & dirty REST API calls with Swift 2.2. See http://grokswift.com/simple-rest-with-swift/
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
// MARK: Using NSURLSession | |
// Get first todo item | |
let todoEndpoint: String = "http://jsonplaceholder.typicode.com/todos/1" | |
guard let url = NSURL(string: todoEndpoint) else { | |
print("Error: cannot create URL") | |
return | |
} | |
let urlRequest = NSURLRequest(URL: url) | |
let config = NSURLSessionConfiguration.defaultSessionConfiguration() | |
let session = NSURLSession(configuration: config) | |
let task = session.dataTaskWithRequest(urlRequest) { | |
(data, response, error) in | |
guard let responseData = data else { | |
print("Error: did not receive data") | |
return | |
} | |
guard error == nil else { | |
print("error calling GET on /todos/1") | |
print(error) | |
return | |
} | |
// parse the result as JSON, since that's what the API provides | |
do { | |
guard let todo = try NSJSONSerialization.JSONObjectWithData(responseData, options: []) as? [String: AnyObject] else { | |
// TODO: handle | |
print("Couldn't convert received data to JSON dictionary") | |
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") | |
} | |
print("The title is: " + todoTitle) | |
} catch { | |
print("error trying to convert data to JSON") | |
} | |
} | |
task.resume() | |
// Create new todo | |
let todosEndpoint: String = "http://jsonplaceholder.typicode.com/todos" | |
guard let todosURL = NSURL(string: todosEndpoint) else { | |
print("Error: cannot create URL") | |
return | |
} | |
let todosUrlRequest = NSMutableURLRequest(URL: todosURL) | |
todosUrlRequest.HTTPMethod = "POST" | |
let newTodo: NSDictionary = ["title": "Frist todo", "body": "I iz fisrt", "userId": 1, "completed": 0] | |
let jsonTodo: NSData | |
do { | |
jsonTodo = try NSJSONSerialization.dataWithJSONObject(newTodo, options: []) | |
todosUrlRequest.HTTPBody = jsonTodo | |
} catch { | |
print("Error: cannot create JSON from todo") | |
return | |
} | |
todosUrlRequest.HTTPBody = jsonTodo | |
let session = NSURLSession() | |
let task = session.dataTaskWithRequest(todosUrlRequest) { | |
(data, response, error) in | |
guard let responseData = data else { | |
print("Error: did not receive data") | |
return | |
} | |
guard error == nil else { | |
print("error calling POST on /todos/1") | |
print(error) | |
return | |
} | |
// parse the result as JSON, since that's what the API provides | |
do { | |
guard let receivedTodo = try NSJSONSerialization.JSONObjectWithData(responseData, | |
options: []) as? [String: AnyObject] else { | |
print("Could not get JSON from responseData as dictionary") | |
return | |
} | |
print("The todo is: " + receivedTodo.description) | |
guard let todoID = receivedTodo["id"] as? Int else { | |
print("Could not get todoID as int from JSON") | |
return | |
} | |
print("The ID is: \(todoID)") | |
} catch { | |
print("error parsing response from POST on /todos") | |
return | |
} | |
} | |
task.resume() | |
// Delete first todo | |
let firstTodoEndpoint: String = "http://jsonplaceholder.typicode.com/todos/1" | |
let firstTodoUrlRequest = NSMutableURLRequest(URL: NSURL(string: firstTodoEndpoint)!) | |
firstTodoUrlRequest.HTTPMethod = "DELETE" | |
let session = NSURLSession() | |
let task = session.dataTaskWithRequest(firstTodoUrlRequest, completionHandler: { | |
(data, response, error) in | |
guard let _ = data else { | |
print("error calling DELETE on /todos/1") | |
return | |
} | |
print("DELETE ok") | |
}) | |
task.resume() | |
// MARK: Using Alamofire | |
// Get first todo | |
let todoEndpoint: String = "http://jsonplaceholder.typicode.com/todos/1" | |
Alamofire.request(.GET, todoEndpoint) | |
.responseJSON { response in | |
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 | |
} | |
guard let value = response.result.value else { | |
print("no result data received when calling GET on /todos/1") | |
return | |
} | |
// handle the results as JSON | |
let todo = JSON(value) | |
// now we have the results, let's just print them though a tableview would definitely be better UI: | |
print("The todo is: " + todo.description) | |
guard let title = todo["title"].string else { | |
print("error parsing /todos/1") | |
return | |
} | |
// to access a field: | |
print("The title is: " + title) | |
} | |
// Create new todo | |
let todosEndpoint: String = "http://jsonplaceholder.typicode.com/todos" | |
let newTodo = ["title": "Frist Psot", "completed": 0, "userId": 1] | |
Alamofire.request(.POST, todosEndpoint, parameters: newTodo, encoding: .JSON) | |
.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 | |
} | |
guard let value = response.result.value else { | |
print("no result data received when calling GET on /todos/1") | |
return | |
} | |
let todo = JSON(value) | |
print("The todo is: " + todo.description) | |
} | |
// Delete first todo | |
let firstTodoEndpoint: String = "http://jsonplaceholder.typicode.com/todos/1" | |
Alamofire.request(.DELETE, firstTodoEndpoint) | |
.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") | |
} |
Hi dooch,
How you're storing the OAuth token looks ok. What kind of error are you getting back when your post fails?
Switched example to use Todo items instead of posts because that was a little confusing.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Fixed postsUrlRequest not being created.