Skip to main content

Create APIManager Class Using Alamofire Swift

Create APIManage.Swift File.



//

//  APIManager.swift

//

//  Created by Dixit Akabari on 7/1/20.

//  Copyright © 2020 Dixit Akabari. All rights reserved.

//


import UIKit

import Alamofire


open class APIManagerNSObject {

    

    // =========== POST API Calling ===========

    

    public class func callPostAPI(param: [StringAny], 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<AnyAFError>, controller: UIViewController, withblock:@escaping (_ response: AnyObject?)->Void) {

        

        switch response.result {

        case .success(let value):

                        

            guard let dic = value asNSDictionary 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.StatusasInt else {

            print("Status Key Not Found")

            return

        }

        

        if (status == 0){

            

            guard let message = data.object(forKey: Message.API_MessageasString else {

                return

            }

            

            print(message)

            

        }else if (status == 1){

            withblock(data.object(forKey: Message.Dataas 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()}

        }

        

    }

    

}



Call Post Method and Get Final Response.



let passingParam = ["key":"value"]

        


        APIManager.callPostAPI(param: passingParam, URlName: "last path of api", controller: self) { (response) in

            print(response) // handle data

        }




Call Get Method and Get Final Response.


let passingParam = ["key":"value"]



APIManager.callGetAPI(param: passingParam, URlName: "last path of api", controller: self) { (response) in

           print(response) // handle data           

        }


Call Multipart Form Data Method and Get Final Response.


let passingParam = ["key":"value"]


APIManager.MultipartFileUpload(param: passingParam, URlName: "last path of api", controller: self) { (response) in

            print(response// handle data 

        }




If you want to cancel all API Call


APIManager.cancleAllAPICall()




Thank you. Happy to Help You.

😊 




Comments

Popular posts from this blog

What is the difference between class and structure in Swift?

  The Main difference in Class and Structure            Classes are reference types.  Structures are value types. Classes have an inheritance that allows one class to inherit the characteristics of another. Structures do not support inheritance. Class ( R eference Types  ) Reference Type When you copy a reference type, each instance shares the data. The reference itself is copied, but not the data it references. When you change one, the other changes too. Inheritance Classes have an inheritance that allows one class to inherit the characteristics of another. Initializer We have to define the initializer manually. Storage Class instances are stored on the heap. Thread Safe Classes are not fully thread − safe. Example :   class EmployeeList { var name: String var age: Int init(name: String, age: Int) { self.name = name self.grade = grade } } let emp1 = EmployeeList(name: "Dixit Akabari", age: 27) let emp2 = emp1 emp2.name = "M

Record UIView In iOS Swift (XCode)

This blog used for helping to Record a UIView.                     It records animations and actions as they happen by taking screen shots of a UIView in a series and then creating a video and saving it to your app’s document folder.  Create  Recorder.swift  File .      This file take screenshot of UIView in a series and save that images in document directory.   import UIKit @objc public class Recorder : NSObject {          var displayLink : CADisplayLink ?     var outputPath : NSString ?     var referenceDate : NSDate ?     var imageCounter = 0          public var view : UIView ?     public var name = "image"     public var outputJPG = false          var imagesArray = [ URL ]()          public func start () {                  if ( view == nil ) {             NSException (name: NSExceptionName (rawValue: "No view set" ), reason: "You must set a view before calling start." , userInfo: nil ). raise ()         }         else {