Skip to content

Instantly share code, notes, and snippets.

@cmoulton
Last active September 9, 2021 21:01
Show Gist options
  • Star 31 You must be signed in to star a gist
  • Fork 10 You must be signed in to fork a gist
  • Save cmoulton/01fdd4fe2c2e9c8195e1 to your computer and use it in GitHub Desktop.
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/
// 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")
}
@cmoulton
Copy link
Author

Updated to Swift 2.0 and Alamofire 2.0.

@cmoulton
Copy link
Author

Switched from ! to guard when creating URL

@cmoulton
Copy link
Author

Updated to Alamofire 3.0.0

@dooch
Copy link

dooch commented Feb 14, 2016

Hi great post.

I am still having trouble getting my oAuth2 POST service to work correctly. Your example doesn't quite call how you handle the Authorisation of the posts?

Would this info be kept in config variable? In my example I am getting the correct access tokens back, but my posts are not quite working? I wonder if you have any pointers in this regard?

` public enum WordPressPostRequest: URLRequestConvertible {
static var baseURLString: String? = wordpressOauth2Settings.baseURL
static var OAuthToken: String?

    case Me()

    public var URLRequest: NSMutableURLRequest { get {
        let URL = NSURL(string: WordPressRequestConvertible.baseURLString!)!
        let mutableURLRequest = NSMutableURLRequest(URL: URL)
        let newPost = "title=MyNewPost"
        mutableURLRequest.HTTPMethod = "POST"
        mutableURLRequest.HTTPBody = newPost.dataUsingEncoding(NSUTF8StringEncoding)

        if let token = WordPressRequestConvertible.OAuthToken {
            mutableURLRequest.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
        }

        return mutableURLRequest
        }
    }
}`

@cmoulton
Copy link
Author

Fixed postsUrlRequest not being created.

@cmoulton
Copy link
Author

Hi dooch,
How you're storing the OAuth token looks ok. What kind of error are you getting back when your post fails?

@cmoulton
Copy link
Author

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