Skip to content

Instantly share code, notes, and snippets.

@rajohns08
Created April 19, 2016 01:12
Show Gist options
  • Save rajohns08/6c873f0dc8ba1afbab4bef9c5e2375f7 to your computer and use it in GitHub Desktop.
Save rajohns08/6c873f0dc8ba1afbab4bef9c5e2375f7 to your computer and use it in GitHub Desktop.
iOS / Swift - Simple RestApi util class
class RestApi {
class func post(request: NSMutableURLRequest, completion: (response: String?, json: AnyObject?) -> ()) {
dataTask(request, method: "POST", completion: completion)
}
class func put(request: NSMutableURLRequest, completion: (response: String?, json: AnyObject?) -> ()) {
dataTask(request, method: "PUT", completion: completion)
}
class func get(request: NSMutableURLRequest, completion: (response: String?, json: AnyObject?) -> ()) {
dataTask(request, method: "GET", completion: completion)
}
class func dataTask(request: NSMutableURLRequest, method: String, completion: (response: String?, json: AnyObject?) -> ()) {
request.HTTPMethod = method
let session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration())
session.dataTaskWithRequest(request) { (data, response, error) -> Void in
if let data = data {
let json = try? NSJSONSerialization.JSONObjectWithData(data, options: [])
let response = String(data: data, encoding: NSUTF8StringEncoding)
completion(response: response, json: json)
} else {
completion(response: "NSURLSessionTimeout", json: nil)
}
}.resume()
}
class func clientUrlRequest(path: String, params: [String: AnyObject]? = nil) -> NSMutableURLRequest {
let request = NSMutableURLRequest(URL: NSURL(string: BaseURL.getFromEnvironment() + "\(path)")!)
if let params = params {
var paramString = ""
for (key, value) in params {
paramString += "\(key)=\(value)&"
}
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.HTTPBody = paramString.dataUsingEncoding(NSUTF8StringEncoding)
}
return request
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment