简体   繁体   中英

Post method request Alamofire

I'm using Swift 3 and Alamofire 4.0.

I want to create similar Alamofire POST request as Postman request shown in screenshot:

在此输入图像描述

I've tried with these lines of code:

var parameters:  [String: Any] = [
    "client_id" : "xxxxxx",
    "client_secret" : "xxxxx",
    "device_token" : "xxxx",
    "fullname" : "xxxxx",
    "gender": "xxx"
]

Alamofire.request(url, method: .post, parameters: parameters).responseJSON { response in
print(response)
}

But I got this error:

在此输入图像描述

How to implement POST request with Body as form-data using Alamofire in Swift 3?

after too much try I have succeded so try this

override func viewDidLoad() {
        super.viewDidLoad()


        let parameters: Parameters = ["client_id": "1","user_token":"xxxxxxxx"]
                // Do any additional setup after loading the view, typically from a nib.
        let url = "http://xxxxxxxxxxx/index.php/Web_api/get_client_profile"
        //let timeParameter =  self.getLastTimeStamp()
        self.request = Alamofire.request(url, method: .post, parameters:parameters)
        if let request = request as? DataRequest {
            request.responseString { response in
                //PKHUD.sharedHUD.hide()
                do{
                    let dictionary = try JSONSerialization.jsonObject(with: response.data!, options: JSONSerialization.ReadingOptions.allowFragments) as! NSDictionary
                    print(dictionary)

                }catch{

                }
            }
        }
    }

    var request: Alamofire.Request? {
        didSet {
            //oldValue?.cancel()
        }
    }
  • Swift 3.0 - Alamofire - Working code for multipart form data upload *

// Parameters

let params: [String : String] =
   ["UserId"    : "\(userID)",
    "FirstName" : firstNameTF.text!,
    "LastName"  : lastNameTF.text!,
    "Email"     : emailTF.text!
   ]

// And upload

Alamofire.upload(
        multipartFormData: { multipartFormData in

            for (key, value) in params
            {
                    multipartFormData.append((value.data(using: .utf8))!, withName: key)
            }
    },
        to: url,
        encodingCompletion: { encodingResult in
            switch encodingResult {
            case .success(let upload, _, _):
                upload.responseJSON { response in
                    debugPrint(response)

                }
                upload.uploadProgress(queue: DispatchQueue(label: "uploadQueue"), closure: { (progress) in


                })

            case .failure(let encodingError):
                print(encodingError)
            }
    }
    )

Let me know if you still have issues with it.

You can post a request using Alamofire.

let url = ""
let headers    = [ "Content-Type" : "application/json"]
let para : Parameters = [ "data" : JSONObject]
Alamofire.request(url, method: .post, parameters: para, encoding: JSONEncoding.default, headers : headers)
    .responseJSON { response in

        print(response)
        print(response.result)

}

Nothing to worry about. Alamofire request method not changed so much(For Swift 3.0) if in case you know how to do that in Swift 2.0/2.2. If you understand the old method then you can easily understand this one also. Now lets take a closer look on the following boilerplate -

Alamofire.request(apiToHit, method: .post, parameters: parametersObject, encoding: JSONEncoding.default, headers: headerForApi).responseJSON { response in switch response.result{

    case .success(_):
        if let receivedData: Any = response.result.value{
            if let statusCode: Int = response.response?.statusCode {
               //Got the status code and data. Do your data pursing task from here.
            }
        }else{
             //Response data is not valid, So do some other calculations here
        }
    case .failure(_):
            //Api request process failed. Check for errors here.
    }

Now here in my case -

  1. apiToHit //Your api url string

  2. .post //Method of the request. You can change this method as per you need like .post, .get, .put, .delete etc.

  3. parametersObject // Parameters needed for this particular api. Same in case you are sending the "body" on postman etc. Remember this parameters should be in form of [String: Any] . If you don't need this then you can just pass nil .

  4. JSONEncoding.default //This the encoding process. In my case I am setting this as .default which is expected here. You can change this to .prettyPrinted also if you need.

  5. headerForApi //This is the header which you want to send while you are requesting the api. In my case it is in [String: String] format. If you don't need this then you can just pass nil .

  6. .responseJSON //Expecting the response as in JSON format. You can also change this as you need.

Now, in my request I am using Switch inside the request closure to check the result like response in switch response.result{ .

Inside case .success(_): case I am also checking for result data and http status code as well like this

if let receivedData: Any = response.result.value{
    if let statusCode: Int = response.response?.statusCode {
 }
}

Hope this helped. Thanks.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM