Created
September 13, 2018 05:57
-
-
Save dilipiOSDeveloper/a71fd5f0f3c102723e719c2afe458a87 to your computer and use it in GitHub Desktop.
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
import UIKit | |
struct RequestType { | |
static let POST = "POST" | |
static let GET = "GET" | |
} | |
enum HtttpType: String { | |
case POST = "POST" | |
case GET = "GET" | |
} | |
class APIManager: NSObject { | |
static let sharedInstance: APIManager = { | |
let instance = APIManager() | |
return instance | |
}() | |
// First Method | |
public func requestApiWithDictParam(dictParam: Dictionary<String,Any>, apiName: String,requestType: String, isAddCookie: Bool, completionHendler:@escaping (_ response:Dictionary<String,AnyObject>?, _ error: NSError?, _ success: Bool)-> Void) { | |
var apiUrl = “” // Your api url | |
apiUrl = apiUrl.appendingFormat("%@", apiName) | |
let config = URLSessionConfiguration.default | |
let session = URLSession(configuration: config) | |
let url = URL(string: apiUrl)! | |
let HTTPHeaderField_ContentType = "Content-Type" | |
let ContentType_ApplicationJson = "application/json" | |
var request = URLRequest.init(url: url) | |
request.timeoutInterval = 60.0 | |
request.cachePolicy = URLRequest.CachePolicy.reloadIgnoringLocalCacheData | |
request.addValue(ContentType_ApplicationJson, forHTTPHeaderField: HTTPHeaderField_ContentType) | |
request.httpMethod = requestType | |
print(apiUrl) | |
print(dictParam) | |
let dataTask = session.dataTask(with: request) { (data, response, error) in | |
if error != nil { | |
completionHendler(nil, error as NSError?, false) | |
} do { | |
let resultJson = try JSONSerialization.jsonObject(with: data!, options: []) as? [String:AnyObject] | |
print("Request API = ", apiUrl) | |
print("API Response = ",resultJson ?? "") | |
completionHendler(resultJson, nil, true) | |
} catch { | |
completionHendler(nil, error as NSError?, false) | |
} | |
} | |
dataTask.resume() | |
} | |
// Second Method | |
public func requestApiWithUrlString(param: String, apiName: String,requestType: String, isAddCookie: Bool, completionHendler:@escaping (_ response:Dictionary<String,AnyObject>?, _ error: NSError?, _ success: Bool)-> Void ) { | |
var apiUrl = "" // Your api url | |
let config = URLSessionConfiguration.default | |
let session = URLSession(configuration: config) | |
var request: URLRequest? | |
if requestType == "GET" { | |
apiUrl = String(format: "%@%@&%@", YourAppBaseUrl,apiName,param) | |
apiUrl = apiUrl.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)! | |
print("URL=",apiUrl) | |
let url = URL(string: apiUrl)! | |
request = URLRequest.init(url: url) | |
request?.httpMethod = "GET" | |
} else { | |
apiUrl = String(format: "%@%@", YourAppBaseUrl,apiName) | |
apiUrl = apiUrl.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)! | |
print("URL=",apiUrl) | |
let bodyParameterData = param.data(using: .utf8) | |
let url = URL(string: apiUrl)! | |
request = URLRequest(url: url) | |
request?.httpBody = bodyParameterData | |
request?.httpMethod = "POST" | |
} | |
request?.timeoutInterval = 60.0 | |
request?.cachePolicy = URLRequest.CachePolicy.reloadIgnoringLocalCacheData | |
request?.httpShouldHandleCookies = true | |
let dataTask = session.dataTask(with: request!) { (data, response, error) in | |
if error != nil { | |
completionHendler(nil, error as NSError?, false) | |
} do { | |
if data != nil { | |
let resultJson = try JSONSerialization.jsonObject(with: data!, options: []) as? [String:AnyObject] | |
print("Request API = ", apiUrl) | |
print("API Response = ",resultJson ?? "") | |
completionHendler(resultJson, nil, true) | |
} else { | |
completionHendler(nil, error as NSError?, false) | |
} | |
} catch { | |
completionHendler(nil, error as NSError?, false) | |
} | |
} | |
dataTask.resume() | |
} | |
} | |
// Here is example of calling Post API from any class | |
let bodyParameters = String(format: "appid=%@&appversion=%@","1","1") | |
APIManager.sharedInstance.requestApiWithUrlString(param: bodyParameters, apiName: "PASS_API_NAME", requestType: HtttpType.POST.rawValue, isAddCookie: false) { (dictResponse, error, success) in | |
if success { | |
if let dictMessage = dictResponse?["message"] as? Dictionary<String, AnyObject> { | |
// do you work | |
} | |
} else { | |
print("Something went wrong...") | |
} | |
} | |
} | |
/// Or just use simple function | |
func dataRequest() { | |
let urlToRequest = "" // Your API url | |
let url = URL(string: urlToRequest)! | |
let session4 = URLSession.shared | |
let request = NSMutableURLRequest(url: url) | |
request.httpMethod = "POST" | |
request.cachePolicy = NSURLRequest.CachePolicy.reloadIgnoringCacheData | |
let paramString = "data=Hello" | |
request.httpBody = paramString.data(using: String.Encoding.utf8) | |
let task = session4.dataTask(with: request as URLRequest) { (data, response, error) in | |
guard let _: Data = data, let _: URLResponse = response, error == nil else { | |
print("*****error") | |
return | |
} | |
if let dataString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue) { | |
print("****Data: \(dataString)") //JSONSerialization | |
} | |
} | |
task.resume() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment