Skip to content

Instantly share code, notes, and snippets.

@paulomcnally
Created December 24, 2015 05:48
Show Gist options
  • Save paulomcnally/5e20b5b0e0223fad5e7f to your computer and use it in GitHub Desktop.
Save paulomcnally/5e20b5b0e0223fad5e7f to your computer and use it in GitHub Desktop.
do {
request.HTTPBody = try NSJSONSerialization.dataWithJSONObject(body, options: NSJSONWritingOptions.init(rawValue: 2))
} catch {
// Error Handling
print("NSJSONSerialization Error")
return
}
import Foundation
class Request {
let session: NSURLSession = NSURLSession.sharedSession()
// GET METHOD
func get(url: NSURL, completionHandler: (NSData?, NSURLResponse?, NSError?) -> Void) {
let request: NSMutableURLRequest = NSMutableURLRequest(URL: url)
request.HTTPMethod = "GET"
request.addValue("application/json", forHTTPHeaderField: "Accept")
session.dataTaskWithRequest(request, completionHandler: completionHandler).resume()
}
// PUT METHOD
func post(url: NSURL, body: NSMutableDictionary, completionHandler: (NSData?, NSURLResponse?, NSError?) -> Void) {
let request: NSMutableURLRequest = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
do {
request.HTTPBody = try NSJSONSerialization.dataWithJSONObject(body, options: NSJSONWritingOptions.init(rawValue: 2))
} catch {
// Error Handling
print("NSJSONSerialization Error")
return
}
session.dataTaskWithRequest(request, completionHandler: completionHandler).resume()
}
// POST METHOD
func put(url: NSURL, body: NSMutableDictionary, completionHandler: (NSData?, NSURLResponse?, NSError?) -> Void) {
let request: NSMutableURLRequest = NSMutableURLRequest(URL: url)
request.HTTPMethod = "PUT"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
do {
request.HTTPBody = try NSJSONSerialization.dataWithJSONObject(body, options: NSJSONWritingOptions.init(rawValue: 2))
} catch {
// Error Handling
print("NSJSONSerialization Error")
return
}
session.dataTaskWithRequest(request, completionHandler: completionHandler).resume()
}
// DELETE METHOD
func delete(url: NSURL, completionHandler: (NSData?, NSURLResponse?, NSError?) -> Void) {
let request: NSMutableURLRequest = NSMutableURLRequest(URL: url)
request.HTTPMethod = "DELETE"
request.addValue("application/json", forHTTPHeaderField: "Accept")
session.dataTaskWithRequest(request, completionHandler: completionHandler).resume()
}
}
let request: Request = Request()
let url: NSURL = NSURL(string: "https://api.example.com/path/to/resource")!
let body: NSMutableDictionary = NSMutableDictionary()
body.setValue("value", forKey: "key")
request.post(url, body: body, completionHandler: { data, response, error in
// code
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment