How to send POST parameters in Swift?

Update to Swift 4.2

This code is based on pixel's answer, and is meant as an update for Swift 4.2

let bodyData = "key1=value&key2=value&key3=value"
request.httpBody = bodyData.data(using: .utf8)

No different than in Objective-C, HTTPBody expects an NSData object:

var bodyData = "key1=value&key2=value&key3=value"
request.HTTPBody = bodyData.dataUsingEncoding(NSUTF8StringEncoding);

You'll have to setup the values & keys yourself in the string.


class func postMethod (params: [String : AnyObject], apikey: String, completion: @escaping (Any) -> Void, failure:@escaping (Error) -> Void)
{
    if Utils().isConnectedToNetwork() == false
    {
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.1, execute: {
            Utils().HideLoader()
        })
        return
    }

    let strURL = Constants.BASE_URL + apikey
    let url = URL(string: strURL)
    print(params)
    print(strURL)

    var token = String()

    if((Constants.USERDEFAULTS .value(forKey: "token")) != nil){

        token = Constants.USERDEFAULTS.value(forKey: "token") as! String
    }
    else{
         token = ""
    }

    let headers = [
        "Authorization": "Bearer \(token)",
        "Accept": "application/json"
    ]


    let manager = Alamofire.SessionManager.default
    manager.session.configuration.timeoutIntervalForRequest = 120
    manager.request(url!, method: .post, parameters: params, headers: headers)
        .responseJSON
        {
            response in
            switch (response.result)
            {
            case .success:
                let jsonResponse = response.result.value as! NSDictionary
                print(jsonResponse)
                completion(jsonResponse)
                Utils().HideLoader()
            case .failure(let error):
                Utils().showAlert("Something went wrong")
                Utils().HideLoader()
                failure(error)
                break
        }
    }
}

Tags:

Ios

Swift