API call formate




import Foundation
import Alamofire

class APIClient {
    
    internal typealias CompletionBlock = (_ data:NSDictionary?,_ error:NSError?) -> Void
    
    // MARK: - Main Common Methos
    fileprivate class func executePostAPICallWithMethod(method:String ,withParameters parameters:AnyObject?, callback:@escaping CompletionBlock) {
        
        let str = ApiConstants.kBaseURL + method
        
        Alamofire.request(str, method: .post, parameters: parameters as? [String : AnyObject]).responseJSON { response in
            switch response.result {
            case .success(let JSON):
                
                let response = JSON as! NSDictionary
                print(response)
                callback(response,nil)
                break
                
            case .failure(let error):
                print("Request failed with error: \(error)")
                callback(response.result.value as? NSMutableDictionary,error as NSError?)
                break
            }
            }
            .responseString { response in
                print("Response String: \(String(describing: response.result.value)) for Method : \(method) with paramater \(parameters)")
        }
    }
    
    fileprivate class func executePostAPICallWithHeaderMethod(method:String ,withParameters parameters:AnyObject?, callback:@escaping CompletionBlock) {
        
        let str = ApiConstants.kBaseURL + method
        
        var header = [String:String]()
        let ud = UserDefaults.standard
        header.updateValue(ud.value(forKey: Key.KeyAuthenticationToken) as! String, forKey: "Authorizations")
        header.updateValue(ud.value(forKey: LoginUser.login_user_userID) as! String, forKey: "UserId")
        print("Header Parameters :- \(header)")
        Alamofire.request(str, method: .post, parameters: parameters as? [String : AnyObject], headers: header).responseJSON{ response in
            switch response.result {
            case .success(let JSON):
                
                let response = JSON as! NSDictionary
                
                callback(response,nil)
                break
                
            case .failure(let error):
                callback(response.result.value as? NSMutableDictionary,error as NSError?)
                break
            }
            }
            .responseString { response in
                print("Response String: \(String(describing: response.result.value)) for Method : \(method) with paramater \(parameters)")

        }
    }
    
    fileprivate class func executePutAPICallWithHeaderMethod(method:String ,withParameters parameters:AnyObject?, callback:@escaping CompletionBlock) {
        
        let str = ApiConstants.kBaseURL + method
        
        var header = [String:String]()
        let ud = UserDefaults.standard
        header.updateValue(ud.value(forKey: Key.KeyAuthenticationToken) as! String, forKey: "Authorizations")
        header.updateValue(ud.value(forKey: LoginUser.login_user_userID) as! String, forKey: "UserId")

        Alamofire.request(str, method: .put, parameters: parameters as? [String : AnyObject], headers: header).responseJSON{ response in
            switch response.result {
            case .success(let JSON):
                
                
                let response = JSON as! NSDictionary
                
                callback(response,nil)
                break
                
            case .failure(let error):
                
                callback(response.result.value as? NSMutableDictionary,error as NSError?)
                break
            }
            }
            .responseString { response in
                print("Response String: \(String(describing: response.result.value)) for Method : \(method) with paramater \(parameters)")

                
        }
    }
    
    fileprivate class func executeGetAPICallWithMethod(method:String, withParameters parameters:AnyObject?, callback:@escaping CompletionBlock) {
        
        let str = ApiConstants.kBaseURL + method
        
        Alamofire.request(str, method: .get, parameters: parameters as? [String : AnyObject], headers: nil).responseJSON{ response in
            print(response.result)
            switch response.result {
            case .success(let JSON):
                
                
                let response = NSMutableDictionary(dictionary: JSON as! [AnyHashable: Any])
                
                callback(response,nil)
                break
                
            case .failure(let error):
                
                callback(response.result.value as? NSMutableDictionary,error as NSError?)
                break
            }
            }
            .responseString { response in
                print("Response String: \(String(describing: response.result.value)) for Method : \(method) with paramater \(parameters)")

                
        }
    }
    
    fileprivate class func executeGetAPICallWithHeaderMethod(method:String, callback:@escaping CompletionBlock) {
        let str = ApiConstants.kBaseURL + method
        
        var header = [String:String]()
        let ud = UserDefaults.standard
        header.updateValue(ud.value(forKey: Key.KeyAuthenticationToken) as! String, forKey: "Authorizations")
        header.updateValue(ud.value(forKey: LoginUser.login_user_userID) as! String, forKey: "UserId")
        
        Alamofire.request(str, method: .get, parameters: nil, headers: header).responseJSON{ response in
            switch response.result {
            case .success(let JSON):
                
                let response = NSMutableDictionary(dictionary: JSON as! [AnyHashable: Any])
                
                callback(response,nil)
                break
                
            case .failure(let error):
                
                callback(response.result.value as? NSMutableDictionary,error as NSError?)
                break
            }
            }
            .responseString { response in
                print("Response String: \(String(describing: response.result.value))")

        }
    }
    
    
    fileprivate class func executeGetAPICallWithHeaderMethodAndWithComponents(method:URL, callback:@escaping CompletionBlock) {
        
        var header = [String:String]()
        let ud = UserDefaults.standard
        header.updateValue(ud.value(forKey: Key.KeyAuthenticationToken) as! String, forKey: "Authorizations")
        header.updateValue(ud.value(forKey: LoginUser.login_user_userID) as! String, forKey: "UserId")

        Alamofire.request(method, method: .get, parameters: nil, headers: header).responseJSON{ response in
            switch response.result {
            case .success(let JSON):
                
                let response = NSMutableDictionary(dictionary: JSON as! [AnyHashable: Any])
                
                callback(response,nil)
                break
                
            case .failure(let error):
                
                callback(response.result.value as? NSMutableDictionary,error as NSError?)
                break
            }
            }
            .responseString { response in
                print("Response String: \(String(describing: response.result.value))")

        }
    }
    
    fileprivate class func executeDeleteAPICallWithHeaderMethod(method:String ,withParameters parameters:AnyObject?, callback:@escaping CompletionBlock) {
        
        let str = ApiConstants.kBaseURL + method
        
        var header = [String:String]()
        let ud = UserDefaults.standard
        header.updateValue(ud.value(forKey: Key.KeyAuthenticationToken) as! String, forKey: "Authorizations")
        header.updateValue(ud.value(forKey: LoginUser.login_user_userID) as! String, forKey: "UserId")
        
        Alamofire.request(str, method: .delete, parameters: parameters as? [String : AnyObject], headers: header).responseJSON{ response in
            switch response.result {
            case .success(let JSON):
                
                
                let response = JSON as! NSDictionary
                
                callback(response,nil)
                break
                
            case .failure(let error):
                
                callback(response.result.value as? NSMutableDictionary,error as NSError?)
                break
            }
            }
            .responseString { response in
        }
    }
    
    fileprivate class func executeUploadAPICallWithHeaderMethod(arrFile: NSMutableArray,method:String ,withParameters parameters: [String : Any], callback:@escaping CompletionBlock) {

        
        let str = ApiConstants.kBaseURL + method
        
        var header = [String:String]()
        let ud = UserDefaults.standard
        header.updateValue(ud.value(forKey: Key.KeyAuthenticationToken) as! String, forKey: "Authorizations")
        header.updateValue(ud.value(forKey: LoginUser.login_user_userID) as! String, forKey: "UserId")

        Alamofire.upload(multipartFormData: { (multipartFormData) in
            for (key, value) in parameters {
                print("Key \(key) Value \(value)")
                multipartFormData.append("\(value)".data(using: String.Encoding.utf8)!, withName: key as String)
            }
            
            if arrFile.count > 0
            {
                for i in 0..<arrFile.count
                {
                    let dictTemp : NSMutableDictionary = arrFile.object(at: i) as! NSMutableDictionary
                    
                    let imageData : NSData = dictTemp.value(forKey: "imageData") as! NSData
                    let name : String = dictTemp.value(forKey: "name") as! String
                    let fileName : String = dictTemp.value(forKey: "fileName") as! String
                    let mimeType : String = dictTemp.value(forKey: "mimeType") as! String
                    multipartFormData.append((imageData as? Data)!, withName: name, fileName: fileName, mimeType: mimeType)
                }
            }
            
        },to:str ,method : .post , headers: header) { (result) in
            
            switch result {
            case .success(let upload, _, _):
                upload.uploadProgress(closure: { (progress) in
                    print("Upload Progress: \(progress.fractionCompleted)")
                })
                
                upload.responseJSON { response in
                    print(response.result.value)
                    callback(response.result.value as? NSDictionary,nil)
                    
                }
            case .failure(let error):
                callback(result as? NSDictionary,error as NSError?)
            }
        }
    }
    
    
    fileprivate class func executeVideoUploadAPICallWithHeaderMethod(arrFile: NSMutableArray,method:String ,withParameters parameters: [String : Any], callback:@escaping CompletionBlock) {
        
        
        let str = ApiConstants.kBaseURL + method
        
        var header = [String:String]()
        let ud = UserDefaults.standard
        header.updateValue(ud.value(forKey: Key.KeyAuthenticationToken) as! String, forKey: "Authorizations")
        header.updateValue(ud.value(forKey: LoginUser.login_user_userID) as! String, forKey: "UserId")
        
        Alamofire.upload(multipartFormData: { (multipartFormData) in
            for (key, value) in parameters {
                print("Key \(key) Value \(value)")
                multipartFormData.append("\(value)".data(using: String.Encoding.utf8)!, withName: key as String)
            }
            
            if arrFile.count > 0
            {
                for i in 0..<arrFile.count
                {
                    let dictTemp : NSMutableDictionary = arrFile.object(at: i) as! NSMutableDictionary
                    
                    let imageData : NSData = dictTemp.value(forKey: "imageData") as! NSData
                    let name : String = dictTemp.value(forKey: "name") as! String
                    let fileName : String = dictTemp.value(forKey: "fileName") as! String
                    let mimeType : String = dictTemp.value(forKey: "mimeType") as! String
                    multipartFormData.append((imageData as? Data)!, withName: name, fileName: fileName, mimeType: mimeType)
                }
            }
            
        },to:str ,method : .post , headers: header) { (result) in
            
            switch result {
            case .success(let upload, _, _):
                upload.uploadProgress(closure: { (progress) in
                    print("Upload Progress: \(progress.fractionCompleted)")
                    UserDefaults.standard.set(Float(progress.fractionCompleted), forKey: "progress")
                    
                    if !(Application.Delegate.navController.topViewController is WorldVC)
                    {
                        if progress.fractionCompleted >= 1.0 || progress.fractionCompleted >= 1
                        {
                            
                            let arrTemp: NSMutableArray = ManagerClass.sharedInstance.getUserUploadData().mutableCopy() as! NSMutableArray
                            if arrTemp.count != 0
                            {
                                if arrTemp.count != 0
                                {
                                    let dictCat: NSDictionary = (arrTemp[0] as? NSDictionary)!
                                    let videoData  = NSMutableArray.init(array: dictCat.value(forKey: "video_data") as! NSArray)
                                    Application.Delegate.EventisUploading = true
                                    let channel_ids  = dictCat.value(forKey: "channel_ids") as? String
                                    
                                    let dicEditProfile : NSMutableDictionary = NSMutableDictionary()
                                    
                                    dicEditProfile.setValue(channel_ids, forKey: "channel_ids")
                                    
                                    print(dicEditProfile)
                                    
                                    UserDefaults.standard.set(0.0, forKey: "progress")
                                    APIClient.addVideoPost(Detail: dicEditProfile as NSDictionary, ImageData: videoData) { (data, error) in
                                    }
                                    arrTemp.removeObject(at: 0)
                                    ManagerClass.sharedInstance.SetUserDefaults(Key: "video", value: arrTemp)
                                    return
                                }
                                
                            }
                            else
                            {
                                UIAlertController.showAlert(in: Application.Delegate.navController.topViewController!, withTitle: "CruiseUp", message: "Video uploaded successfully", cancelButtonTitle: "OK", destructiveButtonTitle: nil, otherButtonTitles: nil, tap: { (controller, action, buttonIndex) in
                                })
                                Application.Delegate.EventisUploading = false
                            }
                        }
                    }
                })
                upload.responseJSON { response in
                    print(response.result.value)
                    if (Application.Delegate.navController.topViewController is HomeVC) {
                        NotificationCenter.default.post(name: NSNotification.Name("reloadStroyView"), object: nil)
                    }
                    callback(response.result.value as? NSDictionary,nil)
                }
            case .failure(let error):
                print(result)
                callback(result as? NSDictionary,error as NSError?)
            }
        }
    }



    //MARK: - Post Text
    class func searchNameAndChannelName(Detail detail : NSDictionary , completion:@escaping CompletionBlock) {
        self.executePostAPICallWithHeaderMethod(method: "APIMethodName", withParameters:detail) { (data, error) -> Void in
            completion(data,error)
        }
    }

    //MARK: - Post Image    
    class func imageUpload(Detail detail : NSDictionary, ImageData arrFile: NSMutableArray,completion:@escaping CompletionBlock) {
        self.executeUploadAPICallWithHeaderMethod(arrFile: arrFile, method: "APIMethodName", withParameters: detail as! [String : Any]) { (data, error) -> Void in
            completion(data,error)
        }
    }

}


Used it


APIClient.searchNameAndChannelName(Detail: dicPara as NSDictionary) { (data, error) in
            self.arrSearchListing = NSArray()
            if((error) != nil) {
                print("getSearchAutoComapleAPI Error : \(error)")
                if((data) != nil){
                    
                } else {
                    
                }
            } else
            {
                print("getSearchAutoComapleAPI Response : \(data)")
                if data?.object(forKey: "status") as! Bool == true {
                    
                }
                else {
                    
                }
            }

        }



APIClient. imageUpload(Detail: dicPara as NSDictionary, arrFile: arrImage) { (data, error) in
            self.arrSearchListing = NSArray()
            if((error) != nil) {
                print("getSearchAutoComapleAPI Error : \(error)")
                if((data) != nil){
                    
                else {
                    
                }
            else
            {
                print("getSearchAutoComapleAPI Response : \(data)")
                if data?.object(forKey: "status"asBool == true {
                    
                }
                else {
                    
                }
            }

        }

Comments

Popular posts from this blog

Windows Keys

how to send invite and give a access of selected application on App Store

how to display popover in TableView cell in swift