Skip to content

Instantly share code, notes, and snippets.

@uniruddh
Last active July 8, 2018 18:55
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save uniruddh/0c20e3e9c039ef81942c to your computer and use it in GitHub Desktop.
Save uniruddh/0c20e3e9c039ef81942c to your computer and use it in GitHub Desktop.
Simple Class for making Rest API calls in swift.
import Foundation
import UIKit
class RestService{
/**
GET respons from REST API.
:param: reqUrl URL of webservice.
:param: completionHandler callback function, this will called once you get response.
*/
func doGet(reqUrl:String, completionHandler:( NSURLResponse?, NSData?, NSError?) -> Void){
//Create request from URL
let urlStringByencoding = reqUrl.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())
let url = NSURL(string: urlStringByencoding!)
print(" Request URL : \(url!)")
let cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData
let request = NSMutableURLRequest(URL: url!, cachePolicy: cachePolicy, timeoutInterval: 20.0)
request.HTTPMethod = "GET"
//Set content type
let contentType = "application/json"
NSURLProtocol.setProperty(contentType, forKey: "Content-Type", inRequest: request)
//You can add any header as below
//request.setValue( "Value", forHTTPHeaderField: "header_key")
// To make Asynchronous Request
let queue:NSOperationQueue = NSOperationQueue()
NSURLConnection.sendAsynchronousRequest(request, queue: queue, completionHandler: completionHandler )
print("GET API called..." )
}
/**
POST REST web-service
:param: reqUrl URL
:param: requestData STRING(PARAMETERS which you want to post to server)
:param: completionHandler callback function, this will called once you get response.
*/
func doPost(reqUrl:String, requestData:String, completionHandler:( NSURLResponse?, NSData?, NSError?) -> Void){
//Create request from URL
let url = NSURL(string: reqUrl)
let cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData
let request = NSMutableURLRequest(URL: url!, cachePolicy: cachePolicy, timeoutInterval: 20.0)
request.HTTPMethod = "POST"
//Set content type
let contentType = "application/json"
NSURLProtocol.setProperty(contentType, forKey: "Content-Type", inRequest: request)
//You can add any header as below
//request.setValue( "Value", forHTTPHeaderField: "header_key")
// set data
let requestBodyData = (requestData as NSString).dataUsingEncoding(NSUTF8StringEncoding)
request.HTTPBody = requestBodyData
// To make Asynchronous Request
let queue:NSOperationQueue = NSOperationQueue()
NSURLConnection.sendAsynchronousRequest(request,
queue: queue,
completionHandler: completionHandler)
/*
// If you want to make annonymous request, you can use following code
// Just unblock this block
{ (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in
// Your code here
if error != nil {
print(error.description)
}
else {
//Converting data to String
var jsonData : NSString = NSString(data:data, encoding:NSUTF8StringEncoding)
// To cast from NSURLResponse to NSHTTPURLResponse for getting http status code
let res = response as NSHTTPURLResponse
let responseCode = res.statusCode
print("Asynchronous Response: \(responseCode)" + " \nand data: \(jsonData)")
}
});
*/
print("POST API called... " )
}
/**
PUT API for UPDATE
:param: reqUrl URL OF WEBSERVICE
:param: requestData STRING(PARAMETERS which you want to post to server)
:param: completionHandler callback function, this will called once you get response.
*/
func doPut(reqUrl:String, requestData:String, completionHandler:( NSURLResponse?, NSData?, NSError?) -> Void){
//Create request from URL
let url = NSURL(string: reqUrl)
let cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData
let request = NSMutableURLRequest(URL: url!, cachePolicy: cachePolicy, timeoutInterval: 20.0)
request.HTTPMethod = "PUT"
//Set content type
let contentType = "application/json"
NSURLProtocol.setProperty(contentType, forKey: "Content-Type", inRequest: request)
//You can add any header as below
//request.setValue( "Value", forHTTPHeaderField: "header_key")
// set data
let requestBodyData = (requestData as NSString).dataUsingEncoding(NSUTF8StringEncoding)
request.HTTPBody = requestBodyData
// To make Asynchronous Request
let queue:NSOperationQueue = NSOperationQueue()
NSURLConnection.sendAsynchronousRequest(request, queue: queue, completionHandler: completionHandler)
print("PUT API called... " )
}
/**
DELETE
:param: reqUrl URL
:param: completionHandler CALLBACK
*/
func doDelete(reqUrl:String, auth:String, completionHandler:( NSURLResponse?, NSData?, NSError?) -> Void){
//Create request from URL
let url = NSURL(string: reqUrl)
let cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData
let request = NSMutableURLRequest(URL: url!, cachePolicy: cachePolicy, timeoutInterval: 20.0)
request.HTTPMethod = "DELETE"
//Set content type
let contentType = "application/json"
NSURLProtocol.setProperty(contentType, forKey: "Content-Type", inRequest: request)
//You can add any header as below
//request.setValue( "Value", forHTTPHeaderField: "header_key")
// To make Asynchronous Request
let queue:NSOperationQueue = NSOperationQueue()
NSURLConnection.sendAsynchronousRequest(request, queue: queue, completionHandler: completionHandler )
print("Delete API called..." )
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment