Extra argument "method" in call. Alamofire - ios

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 {

Related

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
}
}

Extra argument 'method' in call using Alamofire in Swift

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
}

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
}

How to send form-data body with Alamofire [duplicate]

This question already has answers here:
Send POST parameters with MultipartFormData using Alamofire, in iOS Swift
(13 answers)
Closed 5 years ago.
I want to make a request wit Alamofire like this:
postman request
As you can see, i have a parameter called "data" and its value is a Json,
How can i do that using Alamofire?
I have tried with parameters, but doesnt wotk
Alamofire.request(urlservice, method: .post, parameters: ["data": parameters], encoding: JSONEncoding.default, headers: nil).responseJSON { response in
Any suggestions?
UPDATE
Here is my code
var arrayProducts = [[String: String]]()
let product: [String: String] = ["qty": self.txtQty.text!, "precio": self.productPrice, "product_id": self.productId]
arrayProducts.append(product)
let parameters = [
"products": arrayProducts,
"address": self.userInfo["userAddress"]!,
"latitude": "6.157738",
"longitude": "-75.6144665",
"id": 1,
"name": self.userInfo["userName"]!,
"cellphone": self.userInfo["userPhone"]!,
"emei": "23456resdfty"
] as [String : Any]
Alamofire.request(urlservice, method: .post, parameters: ["data": parameters], encoding: JSONEncoding.default, headers: nil).responseJSON { response in
when you have an Any Data as paremeter, you should sent the URLRequest to Alamofire, it supports Any as body
var request = URLRequest(url: URL(string: url)!)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = try! JSONSerialization.data(withJSONObject: parameters, options: [])
Alamofire.request(request)
.responseString { (response) in
// to do anything
}
Here is an example 4 you, the CURL statement an example of what it is doing.
Note token referenced here is a shared secret, obviously not stuff to post to SO :) bags of print statements in here so that you can see what going on/wrong :)
func files_download(sourcePath: String) {
// curl -X POST https://content.dropboxapi.com/2/files/download
// --header "Authorization: Bearer ab-XXX"
// --header "Dropbox-API-Arg: {\"path\": \"/acme101/acme1/acme.png\"}"
var headers:HTTPHeaders!
let subPart: Dictionary = ["path":sourcePath]
do {
let data = try JSONSerialization.data(withJSONObject: subPart, options: [])
let dataString = String(data: data, encoding: .utf8)
headers = ["Authorization": "Bearer " + token, "Dropbox-API-Arg": dataString!]
} catch {
print("Oh fudge")
}
Alamofire.request("https://content.dropboxapi.com/2/files/download", method: .post, encoding: JSONEncoding.init(options: []), headers: headers).responseData(completionHandler: {feedback in
guard feedback.result.value != nil else {
print("Error: did not receive data", //rint("request \(request) feedback \(feedback)"))
return
}
guard feedback.result.error == nil else {
print("error calling POST on list_folder")
print(feedback.result.error)
return
}
if let JSON = feedback.result.value {
print("JSON: \(JSON)")
let dataString = String(data: JSON, encoding: .utf8)
print("JSON: \(JSON) \(String(describing: dataString))")
}
if let IMAGE = feedback.result.value {
print("downloaded \(sourcePath) \(sharedDataAccess.currentSN)")
sharedDataAccess.fnData(index2seek: sharedDataAccess.currentSN, fnData: feedback.result.value! as Data)
NotificationCenter.default.post(name: Notification.Name("previewPane"), object: nil, userInfo: nil)
}
})
}

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