Alamofire POST request with headers
14,233
Solution 1
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
}
}
Solution 2
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)
}
}
Author by
user782400
Updated on June 04, 2022Comments
-
user782400 almost 2 years
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 }