call api in almofire with headers, HTTP Methods, params and callback to called class

151 Views Asked by At

Below function we passed url, parameters,method and message based on this we have to call api and return callback to called function.

this is the url:

http://192.168.0.204/Test/api/DashboardIncomeAndHeadCode/FunGetIncomeOrMenuHeadDetails?StrLocDate=&StrLocRestaurantIds=604808&IntLocCustomerid=6557&StrLocFlag=A&StrLocGroupId=524&StrLocIsIncomeOrMenuHeadCode=I&StrLocFromToDate=

Note : key header use yours also URL and Params use yours this is the for ref

func sendRequestDetailed(uri: String, isShowLoadingView:Bool, params: JSONDictionary?,method: HTTPMethod,message: JSONDictionary?, completionHandler: @escaping (SDNetworkResponse) -> ()) {
    if isShowLoadingView == true {
        DCAppDelegate.showLoadingView()
    }

    let url = urlWithParams(uri: uri, params:params)
    let request = NSMutableURLRequest(url:url as URL)
    request.httpMethod = method.rawValue
    request.timeoutInterval = 120;
    if debugHttp { NSLog("url: \(request.httpMethod) \(url)") }

    if (message != nil) {
        let messageData = try? JSONSerialization.data(withJSONObject: message!, options:[])
        let messageString = NSString(data: messageData!, encoding: String.Encoding.utf8.rawValue)

        request.httpBody = messageData
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        if debugHttp { NSLog("message: \(String(describing: messageString))") }
    }
    request.setValue("KeyValue", forHTTPHeaderField:"Key")
    let headers: HTTPHeaders = [
        "Key": "Value",
    ]

    if (method == .POST) {
        Alamofire.request(uri, method: .post, parameters: params, encoding: JSONEncoding.default).responseJSON { response in
            switch response.result{
            case .success(let value):
                let SDNetworkResponseValue =
                    self.prepareResponseObject(success: response.result.isSuccess, withData: value as Any, andError: response.result.error as NSError? ?? NSError.init(domain: "successfull", code: 1, userInfo: [NSLocalizedDescriptionKey:"request successfull"]))
                DCAppDelegate.removeLoadingView()
                completionHandler(SDNetworkResponseValue )
            case .failure(let error):
                let SDNetworkResponseValue = self.prepareResponseObject(success: response.result.isSuccess, withData: response.result.value as Any , andError: (error as NSError))
                DCAppDelegate.removeLoadingView()
                completionHandler(SDNetworkResponseValue)
            }
        }
    }else if(method == .GET){
        Alamofire.request(uri, method: .get, parameters: params, encoding: JSONEncoding.default,headers:headers).responseJSON { response in
            switch response.result {
            case .success(let value):
                let SDNetworkResponseValue =
                    self.prepareResponseObject(success: response.result.isSuccess, withData: value as Any, andError: response.result.error as NSError? ?? NSError.init(domain: "Error", code: 200, userInfo: [NSLocalizedDescriptionKey:"Something went wrong"]))
                DCAppDelegate.removeLoadingView()
                completionHandler(SDNetworkResponseValue)
            case .failure(let error):
                let SDNetworkResponseValue = self.prepareResponseObject(success: response.result.isSuccess, withData: response.result.value as AnyObject , andError: error as NSError)
                DCAppDelegate.removeLoadingView()
                completionHandler(SDNetworkResponseValue)
            }
        }
    }else if(method == .PUT){
        Alamofire.request(uri, method: .put, parameters: params, encoding: JSONEncoding.default).responseJSON { response in
            switch response.result {
            case .success(let value):
                let SDNetworkResponseValue =
                    self.prepareResponseObject(success: response.result.isSuccess, withData: value as Any, andError: response.result.error as NSError? ?? NSError.init(domain: "Error", code: 200, userInfo: [NSLocalizedDescriptionKey:"Something went wrong"]))
                DCAppDelegate.removeLoadingView()
                completionHandler(SDNetworkResponseValue)
            case .failure(let error):
                let SDNetworkResponseValue = self.prepareResponseObject(success: response.result.isSuccess, withData: response.result.value as AnyObject , andError: error as NSError)
                DCAppDelegate.removeLoadingView()
                completionHandler(SDNetworkResponseValue)
            }
        }
    }else if(method == .DELETE){
        Alamofire.request(uri, method: .delete, parameters: params, encoding: JSONEncoding.default).responseJSON { response in
            switch response.result {
            case .success(let value):
                let SDNetworkResponseValue =
                    self.prepareResponseObject(success: response.result.isSuccess, withData: value as Any, andError: response.result.error as NSError? ?? NSError.init(domain: "Error", code: 200, userInfo: [NSLocalizedDescriptionKey:"Something went wrong"]))
                DCAppDelegate.removeLoadingView()
                completionHandler(SDNetworkResponseValue)
            case .failure(let error):
                let SDNetworkResponseValue = self.prepareResponseObject(success: response.result.isSuccess, withData: response.result.value as AnyObject , andError: error as NSError)
                DCAppDelegate.removeLoadingView()
                completionHandler(SDNetworkResponseValue)
            }
        }
    }
}

but this function always returns error:

▿ FAILURE: Error Domain=NSURLErrorDomain Code=-1001 "The request timed out." UserInfo={NSErrorFailingURLStringKey=http://192.168.0.204/Test/api/DashboardIncomeAndHeadCode/FunGetIncomeOrMenuHeadDetails, _kCFStreamErrorCodeKey=-2102, NSErrorFailingURLKey=http://192.168.0.204/Test/api/DashboardIncomeAndHeadCode/FunGetIncomeOrMenuHeadDetails, NSLocalizedDescription=The request timed out., _kCFStreamErrorDomainKey=4, NSUnderlyingError=0x14da7c50 {Error Domain=kCFErrorDomainCFNetwork Code=-1001 "(null)" UserInfo={_kCFStreamErrorDomainKey=4, _kCFStreamErrorCodeKey=-2102}}}

0

There are 0 best solutions below