Search code examples
iosswift3alamofire

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:

enter image description here

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:

enter image description here

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


Solution

    • 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.