//
// APIManager.swift
//
// Created by Dixit Akabari on 7/1/20.
// Copyright © 2020 Dixit Akabari. All rights reserved.
//
import UIKit
import Alamofire
open class APIManager: NSObject {
// =========== POST API Calling ===========
public class func callPostAPI(param: [String: Any], URlName: String, controller: UIViewController, withblock:@escaping (_ response: AnyObject?)->Void){
//check internet connection available or not
if (AppDelegate.getAppDelegate().connected()) {
let url = "Base_Url" + URlName
//API headers
var _headers : HTTPHeaders = ["Content-Type":"application/x-www-form-urlencoded"]
_headers["Authorization"] = "token" // pass api token here if need
AF.sessionConfiguration.timeoutIntervalForRequest = 60 // request time out time set here
AF.request(url, method:.post, parameters: param,encoding: URLEncoding(),headers: _headers).responseJSON { (response) in
self.checkResponse(response: response, controller: controller) { (data) in
withblock(data)
}
}
}else{
print("Please check your internet connection")
}
}
// ============= GET API Calling =============
public class func callGetAPI(param: [String: Any], URlName :String, controller: UIViewController, withblock:@escaping (_ response: AnyObject?)->Void){
//check internet connection available or not
if (AppDelegate.getAppDelegate().connected()) {
let url = "Base_Url" + URlName
//API headers
var _headers : HTTPHeaders = ["Content-Type":"application/x-www-form-urlencoded"]
_headers["Authorization"] = "token" // pass api token here if need
AF.sessionConfiguration.timeoutIntervalForRequest = 60 // request time out time set here
AF.request(url, method:.get, parameters: param, encoding: URLEncoding(), headers: _headers).responseJSON { response -> Void in
self.checkResponse(response: response, controller: controller) { (data) in
withblock(data)
}
}
}else{
print("Please check your internet connection")
}
}
// ============= Call Multipart For Data API For Upload Images, Files etc.. ================
public class func MultipartFileUpload(param: [String: Any], URlName: String, controller: UIViewController, withblock: @escaping (_ response: AnyObject?)->Void){
if(AppDelegate.getAppDelegate().connected()){
let url = "Base_Url" + URlName
//API headers
var _headers : HTTPHeaders = ["Content-Type":"application/x-www-form-urlencoded"]
_headers["Authorization"] = "token" // pass api token here if need
AF.upload(multipartFormData: { MultipartFormData in
for (key, value) in param {
if let image = value as? UIImage, let logoImgData = image.pngData() {
MultipartFormData.append(logoImgData, withName: key, fileName: "Filename" + ".png", mimeType: "image/jpeg")
}else if let vS = value as? String {
MultipartFormData.append(vS.data(using: String.Encoding.utf8)!, withName: key)
}else if let VI = value as? Int {
MultipartFormData.append(VI.toString().data(using: String.Encoding.utf8)!, withName: key)
}else if let VD = value as? Data {
MultipartFormData.append(VD, withName: key, fileName: "Filename" + ".mp3", mimeType: "audio/*")
}else if let vS = value as? URL {
MultipartFormData.append(vS, withName: key, fileName: "Filename" + ".mp4", mimeType: "video/*")
}
}
}, to: url, method: .post, headers: _headers).responseJSON { (response) in
self.checkResponse(response: response, controller: controller) { (data) in
withblock(data)
}
}
}else{
print("Please check your internet connection")
}
}
// check api response
public class func checkResponse(response: DataResponse<Any, AFError>, controller: UIViewController, withblock:@escaping (_ response: AnyObject?)->Void) {
switch response.result {
case .success(let value):
guard let dic = value as? NSDictionary else {
print("Json Not Valid")
return
}
self.checkResponseStatus(data: dic, controller: controller) { (Dicionary) in
withblock(Dicionary)
}
case .failure(let error):
print(error.localizedDescription)
self.getErrorCodeAndShowError(sender: response.response, controller: controller)
}
}
// Handle All error with code... add error as per your requirement
public class func getErrorCodeAndShowError(sender: HTTPURLResponse?, controller: UIViewController){
if let response = sender {
if response.statusCode == 500 {
print("Under Maintenance: Our server is getting renovated. Come back in a while to watch the new mansion unfold.")
}else if response.statusCode == 404 {
print("Not found: Missing media! The media you're looking for is currently unavailable. Please return if found elsewhere.")
}else if response.statusCode == 429 {
print("Too many requests: Slow down buddy! You're browsing too fast & overspeeding kills (the joy out of the app).")
}else if response.statusCode == 408 {
print("Request Timeout: Time's up! Time runs out for everyone sometimes. Looks like it ran out for this action too.")
}else {
print("Something went Wrong! Please retry")
}
}else{
print("Something went Wrong! Please retry")
}
}
// handle sucess response status you need to change status code as per your requirement
public class func checkResponseStatus(data:NSDictionary, controller:UIViewController, withblock:@escaping (_ response: AnyObject?)->Void) {
guard let status = data.object(forKey: Message.Status) as? Int else {
print("Status Key Not Found")
return
}
if (status == 0){
guard let message = data.object(forKey: Message.API_Message) as? String else {
return
}
print(message)
}else if (status == 1){
withblock(data.object(forKey: Message.Data) as AnyObject?)
}else {
print("Handle Other Status")
}
}
//cancel all api
public class func cancelAllAPICall(){
AF.session.getTasksWithCompletionHandler { (dataTask, uploadTask, downloadTask) in
dataTask.forEach{ $0.cancel()}
uploadTask.forEach{ $0.cancel()}
downloadTask.forEach{ $0.cancel()}
}
}
}
let passingParam = ["key":"value"]
APIManager.callPostAPI(param: passingParam, URlName: "last path of api", controller: self) { (response) in
print(response) // handle data
}
let passingParam = ["key":"value"]
APIManager.callGetAPI(param: passingParam, URlName: "last path of api", controller: self) { (response) in
print(response) // handle data
}
let passingParam = ["key":"value"]
APIManager.MultipartFileUpload(param: passingParam, URlName: "last path of api", controller: self) { (response) in
print(response) // handle data
}
APIManager.cancleAllAPICall()
Thank you. Happy to Help You.
Comments
Post a Comment