Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alamofire POST request with headers

I am trying to make a post request with headers using Alamofire in Swift. However, I keep getting the extra parameter in method call error. I'm using version 4.5 of Alamofire. I'm unable to figure out the error.

Please find the code attached

 let headers = ["Authorization": token, "Content-Type": "application/json"]

 Alamofire.request("http://localhost:8000/create", method: .post,  parameters: parameters, encoding: JSONEncoding.default, headers: headers).responseJSON { response in
}
like image 827
user782400 Avatar asked Oct 24 '25 15:10

user782400


2 Answers

Add Headers in this way

    let headers = ["Authorization" : "Bearer "+accessToken!+"",
                   "Content-Type": "application/json"]



    Alamofire.request(URL, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: headers).responseJSON
            { (response:DataResponse) in
                switch(response.result)
                {
                case .success(let value):
//for Json serialization add in success:

    let JSON = try JSONSerialization.jsonObject(with: response.data! as Data, options:JSONSerialization.ReadingOptions(rawValue: 0))

                            guard let JSONDictionary: NSDictionary = JSON as? NSDictionary else {

                                return
                            }
                        completionHandler(JSONDictionary as? NSDictionary, nil)
                    case .failure(let error):
                        completionHandler(nil, error as NSError?)
                        break
                    }

            }
like image 95
Uma Madhavi Avatar answered Oct 26 '25 05:10

Uma Madhavi


I have used like below and its working for me: -

if let url = URL(string: "http://localhost:8000/create") {
    var urlRequest = URLRequest(url: url)
    urlRequest.httpMethod = HTTPMethod.post.rawValue

    urlRequest.addValue(token, forHTTPHeaderField: "Authorization")
    urlRequest.addValue("application/json", forHTTPHeaderField: "Content-Type")

    Alamofire.request(urlRequest)
        .responseJSON { response in
            self.parseData(response.data!)
    }
}

func parseData(_ data : Data){
        do{
            let readableJSON = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as! [String :AnyObject]
            print("readableJSON : \(readableJSON)")
        }
        catch{
            print(error)
        }
    }
like image 45
Asif Raza Avatar answered Oct 26 '25 06:10

Asif Raza



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!