POST request with data in body with Alamofire 4

前端 未结 4 682
闹比i
闹比i 2020-12-05 07:13

how is it possible to send a POST request with a data in the HTTP body with Alamofire 4? I used custom encoding at swift 2.3 it was working good. I converted my code swift 3

4条回答
  •  借酒劲吻你
    2020-12-05 07:46

    Alamofire for GET and POST method using Alamofire

    1.Create a file named "GlobalMethod" for multiple use

    import Alamofire
    class GlobalMethod: NSObject {
    
        static let objGlobalMethod = GlobalMethod()
    
        func ServiceMethod(url:String, method:String, controller:UIViewController, parameters:Parameters, completion: @escaping (_ result: DataResponse) -> Void) {
    
                var headers = Alamofire.SessionManager.defaultHTTPHeaders
                headers["HeaderKey"] = "HeaderKey"
                if method == "POST" {
                    methodType = .post
                    param = parameters
                }
                else {
                    methodType = .get
                }
                Alamofire.request(url, method: methodType, parameters: param, encoding: JSONEncoding.default, headers:headers
                    ).responseJSON
                    { response in
    
                        completion(response)
                }
            }
    }
    
    1. In the View Controller call "ServiceMethod" created in GlobalMethod by sending values to call API Service

      let urlPath = "URL STRING"
      let methodType = "GET" or "POST" //as you want
      let params:[String:String] = ["Key":"Value"]
      
      GlobalMethod.objGlobalMethod.ServiceMethod(url:urlPath, method:methodType, controller:self, parameters:params)
              {
                  response in
      
                  if response.result.value == nil {
                      print("No response")
                      return
                  }
                  else {
                    let responseData = response.result.value as! NSDictionary
                    print(responseData)
                  }
              }
      

提交回复
热议问题