0

So here is the thing, Im trying to use Almofire to post header and a body (as string) to an API.

_ = Alamofire.request("http://myurl", method: .post, parameters: param, encoding: JSONEncoding.default, headers: ["Authorization" : token])

        .responseJSON { response in


            switch response.result {
            case .success(let data):
                let json = JSON(data)

                print(json)



            case .failure( let error):
                _ = SweetAlert().showAlert("Data Error!", subTitle: "Something Is Wrong!! Please contact Support", style: AlertStyle.warning)
            }}

this works fine..

However I cant figure out how to pass a body string (this is the ID i pass to get data) API does not accept any parametrs (as key value or json) unless if it is just a String (ID). any help would be greatly appreciated.

Tendy
  • 1
  • 1

2 Answers2

2

Add custom parameter like below

var customParameters = [String : String]()  
customParameters["key1"] = "Value1"  
customParameters["key2"] = "Value2"

_ = Alamofire.request("http://myurl", method: .post, parameters: customParameters, encoding: JSONEncoding.default, headers: ["Authorization" : token])

    .responseJSON { response in


        switch response.result {
        case .success(let data):
            let json = JSON(data)

            print(json)



        case .failure( let error):
            _ = SweetAlert().showAlert("Data Error!", subTitle: "Something Is Wrong!! Please contact Support", style: AlertStyle.warning)
        }}
0

I found the answer from https://stackoverflow.com/a/42513496/8099966. this imethod can sed a String value on body. So changed my code like this ..

    struct JSONStringArrayEncoding: ParameterEncoding {
    private let myString: String

    init(string: String) {
        self.myString = string
    }

    func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
        var urlRequest = urlRequest.urlRequest

        let data = myString.data(using: .utf8)!

        if urlRequest?.value(forHTTPHeaderField: "Content-Type") == nil {
            urlRequest?.setValue("application/json", forHTTPHeaderField: "Content-Type")
        }

        urlRequest?.httpBody = data

        return urlRequest!
    }}

then call the API like this...

 _ =  Alamofire.request("http://myurl.com", method: .post, parameters: param, encoding: JSONStringArrayEncoding.init(string: "my String id to send"), headers: ["Authorization" : token])
Tendy
  • 1
  • 1