如何根据API类型发送带有BODY的POST或GET请求

时间:2018-09-27 16:25:28

标签: ios json swift request alamofire

我创建了一个网络管理器类,该类允许通过控制器共享响应实例。根据控制器类型的不同,我调用了定义为GET方法的API,但是在某些情况下,它需要POST方法来发送服务器并等待以授予令牌身份验证开始的响应。

在网络管理器类中,我创建了调用HttpRequest的函数

   func callingHttpRequest(params:Dictionary<String,Any>, apiname:String,cuurentView:UIViewController,taskCallback: @escaping (Int,
        AnyObject?) -> Void)  {

        let urlString  = HOST_NAME + apiname

        print("url",urlString)
        print("params", params)
        Alamofire.request(urlString,method: .get,parameters:params).validate().responseJSON { response in
            switch response.result {
            case .success(let resultData):
                taskCallback(1,resultData as AnyObject)
                break
            case .failure(let error):

                 let returnData = String(data: response.data! , encoding: .utf8)
                 print("returnData" ,returnData)
                print("request URL", response.request)

                if !Connectivity.isConnectedToInternet(){
                    NetworkManager.sharedInstance.dismissLoader()
                    cuurentView.view.isUserInteractionEnabled = true
                    let AC = UIAlertController(title: "Warning", message: error.localizedDescription, preferredStyle: .alert)
                    let okBtn = UIAlertAction(title: "Retry", style: .default, handler: {(_ action: UIAlertAction) -> Void in
                        taskCallback(2, "" as AnyObject)
                    })
                    let noBtn = UIAlertAction(title: "Cancel", style: .destructive, handler: {(_ action: UIAlertAction) -> Void in
                    })
                    AC.addAction(okBtn)
                    AC.addAction(noBtn)
                    cuurentView.present(AC, animated: true, completion: { _ in })
                }
                else{
                    let errorCode:Int = error._code;
                    if errorCode != -999 && errorCode != -1005{
                        NetworkManager.sharedInstance.dismissLoader()
                        cuurentView.view.isUserInteractionEnabled = true
                        let AC = UIAlertController(title: "Warning", message: error.localizedDescription, preferredStyle: .alert)
                        let okBtn = UIAlertAction(title: "Retry", style: .default, handler: {(_ action: UIAlertAction) -> Void in
                            taskCallback(2, "" as AnyObject)
                        })
                        let noBtn = UIAlertAction(title: "Cancel", style: .destructive, handler: {(_ action: UIAlertAction) -> Void in
                        })
                        AC.addAction(okBtn)
                        AC.addAction(noBtn)


                        cuurentView.present(AC, animated: true, completion: { _ in })
                   }else if errorCode == -1005{
                       NetworkManager.sharedInstance.dismissLoader()
                       taskCallback(2, "" as AnyObject)
                    }

                }
                break;

            }


        }

    }

在ViewController中,我正在调用tokenRequest函数来创建从服务器授予的令牌。

func tokenRequest(){
    var tokenRequest = [String:String]();
    tokenRequest["Authorization"] = token_auth;
    tokenRequest["token_id"] = "token_id";
    tokenRequest["token_id"] = "token_id";
    NetworkManager.sharedInstance.callingHttpRequest(params:tokenRequest, apiname:"feed/api/gettoken", cuurentView: self){val,responseObject in
        if val == 1{
            print("responseobjec", responseObject)
            let dict = responseObject as! NSDictionary
            sharedPrefrence.set(dict.object(forKey: "access_token") as! String, forKey: "access_token")
            sharedPrefrence.synchronize();
            self.callingHttppApi()
        }else if val == 2{
            NetworkManager.sharedInstance.dismissLoader()
            self.loginRequest()
        }
    }
}

默认情况下,网络管理器的Alamofire.request(urlString,method: .get,parameters:params)具有方法get,但是功能tokenRequest需要method: .post

我在函数中添加了方法发布

NetworkManager.sharedInstance.callingHttpRequest(params:loginRequest, apiname:"feed/rest_api/gettoken&grant_type=client_credentials", method: .post, cuurentView: self

这返回了错误“调用中的额外参数'方法'”。

1 个答案:

答案 0 :(得分:1)

您的NetworkManager方法签名不包含method作为参数。

您有:

callingHttpRequest(params: Dictionary<String,Any>, 
                  apiname: String, 
              cuurentView: UIViewController, 
             taskCallback: @escaping (Int, AnyObject?) -> Void))

但是,您正在尝试传递不存在的额外method参数时调用它:

callingHttpRequest(params:loginRequest, apiname:"feed/rest_api/gettoken&grant_type=client_credentials", method: .post, // **Does not exist** cuurentView: self) taskCallback: {})

如果要传递method,则需要将该参数添加到方法中以进行调用。