Extra argument 'method' in call using Alamofire in Swift - ios

I'm trying make a request with Alamofire but the errors occurs in parameterer method: HTTPMethod, I used the suggestive parameter .post.
Alamofire.request(OdooAuth.host2!, method: .post, parameters: [String:Any], encoding: JSONEncoding.default, headers: [])
The host is ok because if I try the other way like:
AlamofireXMLRPC.request(OdooAuth.host2!, methodName: "execute_kw", parameters: params)
This works.
The problem is that I want use JSON instead XML.
Error in XCode:
I've searched in many posts on the web, Github, Stackoverflow, but the problems similars not have answer or not solves my problem.

Try This
let _headers = ["Content-Type": "application/json"]
Alamofire.request(url as URL, method: .post, parameters: params, encoding: JSONEncoding.default, headers: _headers).responseJSON { response in
do {
let jsonData = try JSONSerialization.jsonObject(with: response.data!, options: .mutableContainers) as? JSONStandard
if (jsonData != nil) {
let jsonData = response as! Dictionary // PARSE AS PER RESPONSE
} else {
print("No Data")
}
} catch {
print("Error")
}
}

Headers should be a dictionary [:] not an array [], this is why the method signature doesn't match.
try
let headers = [
"Content-Type": "application/json",
"Accept": "application/json"
]
Alamofire.request(url, method: .post, parameters: params, encoding: JSONEncoding.default, headers: headers).responseJSON { response in
// handle the response here
}

Related

Swift 5 & Alamofire 5 : GET method ERROR: Alamofire.AFError.URLRequestValidationFailureReason.bodyDataInGETRequest(22 bytes)

I am trying to get records from Database using Alamofire. I am sending parameters in GET request as below.
let headers : HTTPHeaders = ["x-access-token": "\(t)","username":"\(Base.sharedManager.user)","password":"\(Base.sharedManager.pass)"]
let parm : [String: Any] = ["search_str" : self!.searchStr]
// let searchUrl = Base.sharedManager.URL+"questions/get/"+self!.searchStr
let searchUrl = Base.sharedManager.URL+"questions/get/"
AF.request(searchUrl, method: .get, parameters: parm, encoding:JSONEncoding.default , headers: headers, interceptor: nil).response { (responseData) in
guard let data = responseData.data else {
debugPrint("Error getting question data", responseData.error as Any)
self?.showNoResults()
return
}
do {
let sResults = try JSONDecoder().decode(SearchResults.self, from: data)
self!.searchReturn = [sResults]
self!.qSearchTV.reloadData()
} catch {
self?.showNoResults()
print("Error retriving questions \(error)")
}
}
Got the error below when above code executed:
"Error getting question data" Optional(Alamofire.AFError.urlRequestValidationFailed(reason: Alamofire.AFError.URLRequestValidationFailureReason.bodyDataInGETRequest(23 bytes)))
Use URLEncoding.default instead of JSONEncoding.default
AF.request(path,
method: .get,
parameters: params,
encoding: URLEncoding.default,
headers: nil)
.response { (responseData) in
}
Alamofire 5 and Apple's 2019 frameworks now produce an error when you try to make a GET request with body data, as such a request is invalid. I would suggest checking to make sure that's what your server is expecting, and if it does really require body data for GET requests, reach out to the API provider and request a change, as no device running Apple's 2019 OSes will be able to make such a request.
You have to remove the "parameters" parameter.
Instead of doing this:
AF.request("https://httpbin.org/get",
method: .get,
parameters: [:],
encoding: URLEncoding.httpBody,
headers: [:])
Do this:
AF.request("https://httpbin.org/get",
method: .get,
encoding: URLEncoding.httpBody,
headers: [:])

Post method request Alamofire (responseObject)

I want to create Alamofire POST request
but I get failure response , I dont know the error in mapping object or in the request
func loginUser() {
let URL = ..... + "/Login"
let params2 = "{\"MobileNumber\":\"\(MobileNumber.text!)\"}"
Alamofire.request(URL, method: .post, parameters: [:], encoding: params2, headers: [
"Content-Type": "application/json"]).responseObject { (response: DataResponse<Login>) in
if(response.result.isFailure){
print ("failure")
print (response.result.description)
return
}
else{
print(response.result) // result of response serialization
self.LoginUser = response.result.value
}
}
It looks like you are setting encoding property of the request method to your param2 variable.
Try setting parameter to param2 and update encoding to use .default:
Alamofire.request(URL, method: .post, parameters: param2, encoding: .default, headers: ...
You did not pass proper values into required fields. Use the corrected version below hope it helps
func loginUser() {
let URL = ..... + "/Login"
let params2: [String: Any] = ["MobileNumber" : "\(MobileNumber.text!)"]"
let header = ["Content-Type": "application/json"]
Alamofire.request(URL, method: .post, parameters: params2, encoding: JSONEncoding.default, headers: header).responseObject { (response: DataResponse<Login>) in
if(response.result.isFailure){
print ("failure")
print (response.result.description)
return
}
else{
print(response.result) // result of response serialization
self.LoginUser = response.result.value
}
}

Alamofire post request with body

I am trying to send POST HTTP request with body using Alamofire and would appreciate any help.
My body:
{"data":{"gym":{"country":"USA","city":"San Diego","id":1}}}
Should I do something like this?
let parameters: [String: Any] = [ "data": [
"gym": [
"country":"USA",
"city":"San Diego",
"id":1
]]]
Alamofire.request(URL, method: .post, parameters: parameters, headers: headers())
.responseJSON { response in
print(response)
}
If you wish to send the parameters in json format use encoding as JSONEncoding. So add parameter for encoding in request as follows:
Alamofire.request(URL, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: headers())
.responseJSON { response in
print(response)
}
Hope it helps...
Try this method to convert your json string to dictionary
func convertToDictionary(text: String) -> [String: Any]? {
if let data = text.data(using: .utf8) {
do {
return try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
} catch {
print(error.localizedDescription)
}
}
return nil
}
let str = "{\"data\":{\"gym\":{\"country\":\"USA\",\"city\":\"San Diego\",\"id\":1}}}"
let dict = convertToDictionary(text: str)
and send dictionary as a param in your request.
Alamofire.request(URL, method: .post, parameters: dict, headers: headers())
.responseJSON { response in
print(response)
}
ref : How to convert a JSON string to a dictionary?
What I think is that you should try and prepare your dictionary in the this format:
var gym = [String:Any]()
gym["country"] = "USA"
gym["city"] = "San"
var data = [[String:Any]]()
data.append(gym)
var metaData = [String:Any]()
metaData["data"] = data
Your parameters is wrong...
let parameters: [String: Any] = { "data":
{
"gym": {
"country":"USA",
"city":"San Diego",
"id":1
}
}
}
Alamofire.request(<YOUR-URL>,
method: .post,
parameters: parameters,
encoding: URLEncoding(destination: .queryString),
headers: <YOUR-HEADER>
).validate().responseString { response in
switch response.result {
case .success:
debugPrint("Good to go.")
debugPrint(response)
case .failure:
let errMsg = String(data: response.data!, encoding: String.Encoding.utf8)!
debugPrint(errMsg)
debugPrint(response)
}
}
Hope this help. BTW, in Alamofire 5, debugPrint(response) can print out response.data directly.
You can use the httpBody property of URLRequest along with Alamofire Session request:
var req = try? URLRequest(url: url, method: method, headers: headers)
req?.httpBody = someJson
Alamofire.Session(configuration: .default).request(req!).validate().response { response in
// Handle the response
}

Extra argument "method" in call. Alamofire

I'm using Alamofire to do a get request to Yelp api, i got my post request woking but my get request is not working what so ever, i have tried everything i read from other questions but still no solution. here are my codes.
This is my post request which is working.
class func getAccessToken() {
let parameters: Parameters = ["client_id": client_id, "client_secret": client_secret]
Alamofire.request("https://api.yelp.com/oauth2/token", method: .post, parameters: parameters, encoding: URLEncoding.default, headers: nil).response {
response in
print("Request: \((response.request)!)")
print("Response: \((response.response)!)")
if let data = response.data {
let dict = try! JSONSerialization.jsonObject(with: data, options: []) as! NSDictionary
print("Access Token: \((dict["access_token"])!)")
self.accessToken = (dict["access_token"])! as? String
self.tokenType = (dict["token_type"])! as? String
}
}
}
This is my get request that i'm having trouble with.
class func getRestaurents(searchTerm: String) {
let parameters: Parameters = ["term": searchTerm, "location": "******"]
let headers: HTTPHeaders = [tokenType!: accessToken!]
Alamofire.request("https://api.yelp.com/v3/businesses/search", method: .get, parameters: Parameters, encoding: JSONEncoding.default, headers: headers).response {
response in
if let data = response.data {
let dict = try! JSONSerialization.jsonObject(with: data, options: [] as! [NSDictionary])
print(dict)
}
}
}
Thank you.
You are passing class Parameters instead of its object parameters.
Alamofire.request("https://api.yelp.com/v3/businesses/search", method: .get, parameters: Parameters, encoding: JSONEncoding.default, headers: headers).response {
Should be:
Alamofire.request("https://api.yelp.com/v3/businesses/search", method: .get, parameters: parameters, encoding: JSONEncoding.default, headers: headers).response {

Alamofire not sending the current headers (swift)

I keep getting "error_type":"OAuthException","code":"41" when I using alamofire or even when i made it through to the server I got data from before header's authorisation. I think it keep sending same header, how to make sure that alamofire send the current headers?
let headers = ["Authorization" : "\(AccessToken) \(TokenType)"]
print(headers)
Alamofire.request(.GET, "url/profile/", headers: headers, encoding: .JSON).responseJSON { response in
switch response.result {}
EDIT
First, I use login API
let parameters = [
"client_id": "\(Constant.clientId)",
"client_secret": "\(Constant.clientSecret)",
"response_type": "\(Constant.responseType)",
"scope" : "\(Constant.scope)",
"redirect_uri": "\(Constant.redirect)",
"email": "\(email!)",
"password": "\(pass!)"
]
print(parameters)
Alamofire.request(.POST, "http://url/login/", parameters: parameters, encoding: .JSON).responseJSON { response in
switch response.result {
case .Success:
if let value = response.result.value {
let json = JSON(value)
print("JSON: \(json)")
let accessToken = json["access_token"].string!
let refreshToken = json["refresh_token"].string
let tokenType = json["token_type"].string!
let expiresIn = json["expires_in"].string
}
And then, I use accessToken and tokenType for authorization
if(refreshToken != nil)
{
let headersCust = ["Authorization" : "\(accessToken) \(tokenType)"]
print(headersCust)
Alamofire.request(.GET, "http://goodies.co.id/api/v1/customer/profile/", headers: headersCust, encoding: .JSON).responseJSON { response in {}
Usually this problem is caused by Redirection. Using some networking debugging tool like Proxyman helps you to understand if this is a case; if so :
this is Alamofire 5(AF 5) solution:
let headers: [String:String] = [...]
let params: [String: Any] = [...]
let url = URL(...)
let redirector = Redirector(behavior: Redirector.Behavior.modify({ (task, urlRequest, resp) in
var urlRequest = urlRequest
headers.forEach { header in
urlRequest.addValue(header.value, forHTTPHeaderField: header.key)
}
return urlRequest
}))
//use desired request func of alamofire and your desired enconding
AF.request(url, method: .post, parameters: params, encoding: JSONEncoding.default, headers: headers)
.responseJSON { response in
//handleDataResponse...
}.redirect(using: redirector)
I hope you are using the latest Alamofire so here is the code for .GET Request:
let headers = [
"Authorization": "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==",
"Content-Type": "application/x-www-form-urlencoded"
]
Alamofire.request(.GET, "https://httpbin.org/get", headers: headers)
.responseJSON { response in
debugPrint(response)
}
Reference: https://github.com/Alamofire/Alamofire
Try this out! And make sure you are sending the proper headers.

Resources