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

标签 ios json swift request alamofire

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

在 Network Manager 类中,我创建了调用 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 来创建从服务器授予的 token 。

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”。

最佳答案

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

你有:

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

但是您在传递一个不存在的额外 method 参数时试图调用它:

调用HttpRequest(参数:loginRequest, apiname:"feed/rest_api/gettoken&grant_type=client_credentials", 方法:.post,//**不存在** 当前 View : self ) 任务回调:{})

如果您想传递一个方法,您需要将该参数添加到您的方法中以便调用它。

关于ios - 如何根据 API 类型发送带有 BODY 的 POST 或 GET 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52541367/

相关文章:

iOS7 UIImagePickerController allowsEditing 无法正常工作

javascript - 如何根据 Angularjs 接收到的数据在我的 JSON 对象中创建动态键?

javascript - getJSON 错误 - 不确定我哪里出错了

Swift - 实时更新标签

iphone - imageView tapGesture 与按钮 touchUpInside ,带有 didSelectRowAtIndexPath

ios - 在 iOS 7 中保留 iOS 6 布局进行小更新?

ios - 在 AVAudioSession 中使用蓝牙播放

c# - 如何使用 C# 在 .NET 中获取格式化的 JSON?

swift - 无法更改导航栏高度 ios 11

ios - 快速访问存储在另一个文件夹中的文件