Last active
August 29, 2019 06:22
-
-
Save arjun011/03014886a69e9c206525ee0a7211cacf to your computer and use it in GitHub Desktop.
Post Api using URLSession
This file contains hidden or 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
/** | |
This method is used to call a GET API | |
- Parameter url: A String url to call POST Api. | |
- Parameter param: A Dictionary of API parameters. | |
- Parameter success: A Success block of API response. | |
- Parameter failure: A Failure block of API response. | |
*/ | |
public typealias success = (_ response: JSON) -> Void | |
public typealias failure = (_ error: Error? , _ isTimeOut: Bool) -> Void | |
class func GET(_ url: String, | |
param: [String: Any]?, | |
success: @escaping success, | |
failure: @escaping failure) { | |
UIApplication.shared.isNetworkActivityIndicatorVisible = true | |
guard let serviceUrl = URL(string: url) else { return } | |
var request = URLRequest(url: serviceUrl) | |
request.httpMethod = RequestType.GET.rawValue | |
request.addCommonHeaders() | |
// guard let httpBody = try? JSONSerialization.data(withJSONObject: param, options: []) else { | |
// return | |
// } | |
// request.httpBody = httpBody | |
let session = URLSession.shared | |
let created = Date() | |
session.dataTask(with: request) { (data, response, error) in | |
// Response time | |
let diff = Date().timeIntervalSince(created) | |
print("\(diff) seconds") | |
var responseStatusCode = 0 | |
if let statusCode = (response as? HTTPURLResponse)?.statusCode { | |
responseStatusCode = statusCode | |
} | |
if let response = response { | |
debugPrint(response) | |
} | |
if let data = data { | |
do { | |
let json = try JSONSerialization.jsonObject(with: data, options: []) | |
let responseJSON = JSON(json) | |
DispatchQueue.main.async { | |
success(responseJSON) | |
} | |
guard responseJSON["response_code"].intValue != EHttpStatusCode.OK.rawValue, responseStatusCode != 200, responseStatusCode != 204 else { | |
return | |
} | |
DispatchQueue.main.async { | |
Utils.alertWithSingleButton(message: responseJSON["response_message"].stringValue) | |
} | |
} catch { | |
debugPrint(error) | |
DispatchQueue.main.async { | |
Utils.alertWithSingleButton(message: error.localizedDescription) | |
failure(error, true) | |
} | |
} | |
} | |
}.resume() | |
} |
This file contains hidden or 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
public typealias successResponse = (_ response: JSON, _ statusCode:NSInteger?) -> Void | |
public typealias failure = (_ error: Error? , _ isTimeOut: Bool) -> Void | |
// Common Header File | |
extension URLRequest { | |
mutating func addCommonHeaders() { | |
self.setValue("Application/json", forHTTPHeaderField: "Content-Type") | |
self.setValue("traceapp@jiniguru", forHTTPHeaderField: "APP_REST_USERNAME") | |
self.setValue("Jku@i3!lIdr8v31", forHTTPHeaderField: "APP_REST_PASSWORD") | |
} | |
} | |
/** | |
This method is used to call a POST API | |
- Parameter url: A String url to call POST Api. | |
- Parameter param: A Dictionary of API parameters. | |
- Parameter success: A Success block of API response. | |
- Parameter failure: A Failure block of API response. | |
*/ | |
class func POST(_ url: String, | |
param: [String: Any]?, | |
success: @escaping successResponse, | |
failure: @escaping failure) { | |
//************* | |
UIApplication.shared.isNetworkActivityIndicatorVisible = true | |
guard let serviceUrl = URL(string: url) else { return } | |
var request = URLRequest(url: serviceUrl) | |
request.httpMethod = RequestType.POST.rawValue | |
request.addCommonHeaders() | |
request.setValue("\(SharedManager.sharedInstance.profileSelf.userData?.user?.ricaToken ?? "")", forHTTPHeaderField: "Authorization") | |
guard let httpBody = try? JSONSerialization.data(withJSONObject: param ?? [:], options: []) else { | |
return | |
} | |
request.httpBody = httpBody | |
let session = URLSession.shared | |
let created = Date() | |
session.dataTask(with: request) { (data, response, error) in | |
let diff = Date().timeIntervalSince(created) | |
print("POST New =\(diff) seconds") | |
var responseStatusCode = 0 | |
if let statusCode = (response as? HTTPURLResponse)?.statusCode { | |
print("Valid http Response",statusCode) | |
responseStatusCode = statusCode | |
} | |
if let response = response { | |
print(response) | |
} | |
if let data = data { | |
do { | |
let json = try JSONSerialization.jsonObject(with: data, options: []) | |
debugPrint(json) | |
let responseJSON = JSON(json) | |
DispatchQueue.main.async { | |
success(responseJSON,responseStatusCode) | |
} | |
} catch { | |
debugPrint(error) | |
DispatchQueue.main.async { | |
if responseStatusCode == EHttpStatusCode.NO_CONTENT.rawValue { | |
success(JSON(),responseStatusCode) | |
return | |
} | |
// Utils.alertWithSingleButton(message: error.localizedDescription) | |
// failure(error, true) | |
} | |
} | |
} | |
}.resume() | |
} |
This file contains hidden or 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
/** | |
This method is used to call a POST API | |
- Parameter url: A String url to call POST Api. | |
- Parameter param: A Dictionary of API parameters. | |
- Parameter success: A Success block of API response. | |
- Parameter failure: A Failure block of API response. | |
*/ | |
static let requestHeaders: HTTPHeaders = [ | |
"Content-Type": "application/json", | |
"APP_REST_USERNAME": "traceapp@jiniguru", | |
"APP_REST_PASSWORD": "Jku@i3!lIdr8v31" | |
] | |
class func POSTNEW(_ url: String, | |
param: [String: Any]?, | |
success: @escaping successResponse, | |
failure: @escaping failure) { | |
/// This will show network indicator in status bar | |
UIApplication.shared.isNetworkActivityIndicatorVisible = true | |
Alamofire.request(url, method: HTTPMethod.post, parameters: param, encoding: JSONEncoding(options: []), headers: WSConstant.requestHeaders).responseJSON { response in | |
debugPrint(response) | |
/// This will hide network indicator in status bar | |
UIApplication.shared.isNetworkActivityIndicatorVisible = false | |
switch response.result { | |
case .success: | |
let responseJSON = JSON(response.result.value!) | |
success(responseJSON,response.response?.statusCode) | |
guard responseJSON["response_code"] != 200 ,response.response?.statusCode != 204 ,response.response?.statusCode != 200 else { | |
return | |
} | |
case .failure(let error): | |
/// if Request is upload tm user documents | |
if response.request?.url?.absoluteString == WSConstant.uploadDocuments { | |
failure(error, true) | |
break | |
} | |
if (error as NSError).code == -1001 { | |
print("The request timed out. Pelase try after again.") | |
Utils.alertWithSingleButton(message: error.localizedDescription) | |
failure(error, true) | |
} else if (error as NSError).code == -999 { | |
print("Cancelled Request") | |
} else { | |
print("Somthin went Wrong.") | |
Utils.alertWithSingleButton(message: error.localizedDescription) | |
failure(error, false) | |
} | |
break | |
} | |
} | |
} |
This file contains hidden or 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
/** | |
This method is used to call a PUT API | |
- Parameter url: A String url to call POST Api. | |
- Parameter param: A Dictionary of API parameters. | |
- Parameter success: A Success block of API response. | |
- Parameter failure: A Failure block of API response. | |
*/ | |
class func PUTNEW(_ url: String, | |
param: [String: Any]?, | |
success: @escaping successResponse, | |
failure: @escaping failure) { | |
debugPrint("request Url =",url) | |
// ************ | |
UIApplication.shared.isNetworkActivityIndicatorVisible = true | |
guard let serviceUrl = URL(string: url) else { return } | |
var request = URLRequest(url: serviceUrl) | |
request.httpMethod = RequestType.PUT.rawValue | |
request.setValue("Application/json", forHTTPHeaderField: "Content-Type") | |
request.setValue("\(SharedManager.sharedInstance.profileSelf.userData?.user?.ricaToken ?? "")", forHTTPHeaderField: "Authorization") | |
guard let httpBody = try? JSONSerialization.data(withJSONObject: param, options: []) else { | |
return | |
} | |
request.httpBody = httpBody | |
let session = URLSession.shared | |
let created = Date() | |
session.dataTask(with: request) { (data, response, error) in | |
let diff = Date().timeIntervalSince(created) | |
print("PUT =\(diff) seconds") | |
var responseStatusCode = 0 | |
if let statusCode = (response as? HTTPURLResponse)?.statusCode { | |
print("Valid http Response",statusCode) | |
responseStatusCode = statusCode | |
} | |
if let response = response { | |
print(response) | |
} | |
if let data = data { | |
do { | |
let json = try JSONSerialization.jsonObject(with: data, options: []) | |
debugPrint(json) | |
let responseJSON = JSON(json) | |
DispatchQueue.main.async { | |
success(responseJSON,responseStatusCode) | |
} | |
} catch { | |
debugPrint(error) | |
DispatchQueue.main.async { | |
Utils.alertWithSingleButton(message: error.localizedDescription) | |
failure(error, true) | |
} | |
} | |
} | |
}.resume() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment