Yelp get request not working - ios

When i do the same request in Postman everything is fine but when i try it in Alamofire i get an error.
I'm user Alamofire in swift for the request. Here is my code.
let parameters: Parameters = ["term": searchTerm as AnyObject, "location": "Washington DC" as AnyObject]
// let headers: HTTPHeaders = [tokenType!: accessToken!]
Alamofire.request("https://api.yelp.com/v3/businesses/search", method: .get, parameters: parameters, encoding: JSONEncoding.default, headers: ["Authorization": "Bearer Access_token_************************"])
Error text:
{
error = {
code = "VALIDATION_ERROR";
description = "Please specify a location or a latitude and longitude";
};

Related

alamofire extra argument in call

Facing this issue from past 2 days. I have updated the pod, updated pod version from 4.0.1 to 4.5.0 but the problem is still the same.
here is my code:
var params: Parameters = [:]
params = [
"id": fetchFromCoreData(keyVlue: "trsptrRegistrationId") as AnyObject,
"mobileNumber": fetchFromCoreData(keyVlue: "mobileNO") as AnyObject,
"isNotification": isnotifyTag as AnyObject
]
print(params)
let auth_token = fetchFromCoreData(keyVlue: "Auth_Token")
let headers = [
"authKey": auth_token
]
print(headers)
let URL: String = GlobalUrls.BASE_URL + GlobalUrls.notifySetting
print(URL)
Alamofire.request(URL, method: .post, parameters: params, encoding: JSONEncoding.default, headers: headers)
can you please try this way
var param :Parameters
param = [
"id": "Any id",
"mobileNumber": "any mobile number",
"isNotification": "is notification"
]
print(param)
let auth_token = "your auth_token"
let headers = [
"authKey": auth_token
]
print(headers)
let base_url: String = "Here is my base URL"
print(base_url)
Alamofire.request(base_url, method: .post, parameters: param, encoding: JSONEncoding.default, headers: headers).responseJSON(completionHandler: {(resObj) -> Void in
print(resObj)
if resObj.result.isSuccess
{
print("Sucess result")
}
if resObj.result.isFailure
{
let error : Error = resObj.result.error!
print("Fail result")
print(error.localizedDescription)
}
})

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 {

Receiving MailChimp error "Your request did not include an API key." even though the API key is included using Alamofire

I am using Alamofire to send a request to MailChimp to add a user to a list
MailChimp's docs say:
There are 2 authentication methods for the API: HTTP Basic authentication and OAuth2. The easiest way to authenticate is using HTTP Basic authentication. Enter any string as your username and supply your API Key as the password.
The request I wrote for Alamofire:
let params: [String : AnyObject] = ["email_address": email, "status": "subscribed", "merge_fields": [ "FNAME": name]]
guard let url = "https://us10.api.mailchimp.com/3.0/lists/<listID>/members/".stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding) else { return }
Alamofire.request(.POST, url, parameters: params, encoding: .URL)
.authenticate(user: "apiKey", password: "<apikey>")
.responseJSON { response in
if response.result.isFailure {
}
else if let responseJSON = response.result.value as? [String: AnyObject] {
}
}
I checked that the API key is correct by using it to access their playground:
https://us1.api.mailchimp.com/playground/
The response I get back states that the API key was not included:
Your request did not include an API key.
Where have I gone wrong?
Swift 3
Make sure you take a look at MailChimp's Error Glossary. A 401 indicates that your API key is not being read properly.
For Swift 3, the header construction in Abbey Jackson's answer needs to be updated to this. Otherwise it totally works.
let credentialData = "AnyString:\(apiKey)".data(using: String.Encoding.utf8)!
let base64Credentials = credentialData.base64EncodedString()
let headers = ["Authorization": "Basic \(base64Credentials)"]
Here's an example that uses Request.authorizationHeader instead.
let apiKey: String = "xxxxxxxxxxxxxxx2b-us11" // note the 'us11'
let baseUrl: String = "https://us11.api.mailchimp.com/3.0" // note the 'us11'
let listId: String = "xxxxxx2f"
func createListMember() {
let url = "\(baseUrl)/lists/\(listId)/members"
guard let authorizationHeader = Request.authorizationHeader(user: "AnyString", password: apiKey) else {
print("!authorizationHeader")
return
}
let headers: HTTPHeaders = [
authorizationHeader.key: authorizationHeader.value
]
let parameters: Parameters = [
"email_address": email,
"status": "subscribed"
]
// perform request (make sure you're using JSONEncoding.default)
Alamofire.request(url, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: headers)
//.authenticate(user: "AnyString", password: apiKey) // this doesn't work
.validate()
.responseJSON {(response) in
print(response)
}
}
So MailChimp actually needs the api key sent in the authorization header like this:
let params: [String: AnyObject] = ["email_address": email, "status": "subscribed"]
guard let url = "https://us10.api.mailchimp.com/3.0/lists/<listID>/members/".stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding) else { return }
let credentialData = "user:<apikey>".dataUsingEncoding(NSUTF8StringEncoding)!
let base64Credentials = credentialData.base64EncodedStringWithOptions([])
let headers = ["Authorization": "Basic \(base64Credentials)"]
Alamofire.request(.POST, url, headers: headers, parameters: params, encoding: .URL)
.responseJSON { response in
if response.result.isFailure {
}
else if let responseJSON = response.result.value as? [String: AnyObject] {
}
}
edit: See Derek Soike's answer below for Swift 3
If you are passing the apikey as like bxxxxxxxxxxxxxxxxxxxxxxxxxxxxx5dxf-us10, then you'll get the error as you specified.
Try to pass the apikey by skipping the characters after the hyphen (like "bxxxxxxxxxxxxxxxxxxxxxxxxxxxxx5dxf") and check if it works.
Swift 3 As of Sept. 5, 2017
It says method is an extra argument by accident. It's likely that your encoding part is off. It should look like this:
encoding: JSONEncoding.default

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.

Alamofire Request error only on GET requests

I'm working on transferring my project from AFNetworking to Alamofire. Really like the project. POST requests work just fine, however, I'm receiving this error when attempting to make a GET request.
Here's some example code:
class func listCloudCredntials(onlyNew onlyNew: Bool = true, includePending: Bool = true) -> Request {
let parameters: [String: AnyObject] = includePending ? ["include_pending": "true"] : [:]
let urlString = "https://myapp-staging.herokuapp.com/api/1/credntials"
let token = SSKeychain.storedToken()
let headers: [String: String] = ["Authorization": "Bearer \(token)"]
return Alamofire.request(.GET, urlString, parameters: parameters, encoding: .JSON, headers: headers)
}
I receive this error: : -1005 The network connection was lost
However, if I change the request type to .POST, the request "works". I receive a 401 code, but at least the request doesn't lose Network connection.
What am I doing wrong?
You're encoding the parameters as JSON in the body of the request, try encoding the parameters in the URL by changing the encoding to URL:
return Alamofire.request(.GET, urlString, parameters: parameters, encoding: .URL, headers: headers)
As this is the default behavior, you can simply remove it:
return Alamofire.request(.GET, urlString, parameters: parameters, headers: headers)

Resources