【问题标题】:How to send a POST or GET request with BODY depending on API type如何根据 API 类型使用 BODY 发送 POST 或 GET 请求
【发布时间】:2019-03-03 15:03:00
【问题描述】:

我创建了一个类网络管理器,允许通过控制器共享响应实例。根据控制器类型,我调用定义为方法 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。

我在函数中添加方法post

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

这返回了一个错误“Extra argument 'method' in call”。

【问题讨论】:

    标签: ios json swift request alamofire


    【解决方案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,您需要将该参数添加到您的方法中才能调用它。

    【讨论】:

    • 我试过在callingHTTPRequest中添加方法并没有解决我的问题。
    • Seed 我在 func 中将方法定义为字符串,如下 func callingHttpRequest(params:Dictionary&lt;String,Any&gt;, apiname:String,cuurentView:UIViewController,method:String, taskCallback: @escaping (Int, AnyObject?) -&gt; Void) { 然后我在 ViewController 中将方法保留为默认 Alamofire.request(urlString,method: .get,parameters:params).validate().responseJSON { response 我添加了 method: .post 得到 Type 'String' has no member 'post'
    • 这是一个不同的错误。我的回答解决了你的第一个问题。现在你的问题是你传递了错误的值。 method 应该是 String 类型。您正在尝试传递枚举案例.post。您需要传递 String 或更改参数以接受您要传递的类型。
    • 我通过定义method:HTTPMethod 解决了这个问题,这让我可以在需要时传递.post 或.get。
    • 太好了,如果有帮助,请点赞和/或接受我的回答。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-22
    相关资源
    最近更新 更多