Twitter API in SWIFT via Alamofire - ios

I currently try to send a simple query - in Postman it works fine for me, but in SWIFT I simply cant get it working
My Code looks like:
func TWITTER_getPosts(username:String){
let headers = [
"screen_name": "username",
"authorization": "OAuth oauth_consumer_key=\"<KEY>\",oauth_token=\"<KEY>\",oauth_signature_method=\"HMAC-SHA1\",oauth_timestamp=\"1469246792\",oauth_nonce=\"n6Sxbq\",oauth_version=\"1.0\",oauth_signature=\"<KEY>\"",
"include_rts": "false"
]
Alamofire.request(.GET, "https://api.twitter.com/1.1/statuses/user_timeline.json", parameters: headers)
.responseJSON { response in
print(response.request) // original URL request
print(response.response) // URL response
print(response.data) // server data
print(response.result) // result of response serialization
if let JSON = response.result.value {
print("JSON: \(JSON)")
}
}
}
I Always end in a
errors = (
{
code = 215;
message = "Bad Authentication data.";

One of the parameters for the request method is incorrect.
If you are passing headers, they shouldn't be passed in parameters, they should be passed as the following:
let headers = [
"Authorization": "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==",
"Accept": "application/json"
]
Alamofire.request(.GET, "https://httpbin.org/get", headers: headers)
.responseJSON { response in
debugPrint(response)
}
headers: headers should be the way to go.

Related

Unable to get response from Google distance matrix api

I am using google distance matrix API and i am using following code
let headers: HTTPHeaders = [ "Accept": "application/json", "Content-Type": "application/json" ]
let url = "https://maps.googleapis.com/maps/api/distancematrix/json?&origins=\(start)&destinations=\(end)&key=AIzaSyDvt_KiUCtdb1kPEw4E4Dt68EuiF8PosAg"
let header: HTTPHeaders = [ "Accept": "application/json", "Content-Type": "application/json" ]
Alamofire.request( url, method: .get, encoding: JSONEncoding.default, headers : header) .responseString { response in
print(response.request) // original URL request
print(response.response) // HTTP URL response
print(response.data) // server data
print(response.result)
}
as per this Unable to fetch Response For Google Distance matrix in Swift i am passing header but still i am getting following error.
Here is my URL with start and end
"https://maps.googleapis.com/maps/api/distancematrix/json?&origins=Nanpura, Surat, Gujarat 395008, India&destinations=Adajan, Surat, Gujarat, India&key=AIzaSyDvt_KiUCtdb1kPEw4E4Dt68EuiF8PosAg "
You should encode url, try with this
let url = "https://maps.googleapis.com/maps/api/distancematrix/json?&origins=Nanpura, Surat, Gujarat 395008, India&destinations=Adajan, Surat, Gujarat, India&key=AIzaSyDvt_KiUCtdb1kPEw4E4Dt68EuiF8PosAg"
let encodedUrl = url.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
let header: HTTPHeaders = [ "Accept": "application/json", "Content-Type": "application/json" ]
Alamofire.request(encodedUrl! , method: .get,encoding: JSONEncoding.default, headers: header)
.responseJSON { (data) in
print(data)
}
this will also work,
Alamofire.request(encodedUrl!, method: .get,encoding: JSONEncoding.default, headers: header)
.responseString {response in
print(response.request) // original URL request
print(response.response) // HTTP URL response
print(response.data) // server data
print(response.result)
}
Response will be like this,
SUCCESS: {
"destination_addresses" = (
"Adajan, Surat, Gujarat, India"
);
"origin_addresses" = (
"Nanpura, Surat, Gujarat 395008, India"
);
rows = (
{
elements = (
{
distance = {
text = "2.4 km";
value = 2433;
};
duration = {
text = "6 mins";
value = 373;
};
status = OK;
}
);
}
);
status = OK;
}
I checked the request and it is working fine. I guess you are missing privacy setting in info.plist

Alamofire POST Bad Request

I'm trying to make a post request to my server through Alamofire but it returns a bad request saying that parameters are badly formed. Same requests is working in postman and swagger.
Here is the code:
var params = [
"username": "jora#company.com",
"password": "test123",
"pushToken": "No token"
]
Alamofire.request("https://thankyouposta.com/api/auth", method: .post, parameters: params, encoding: URLEncoding.default, headers: R.Api.headers).responseJSON { response in
switch response.result {
case .success(let value):
// ...
case .failure(let error):
// ...
}
}
Update 1
Parameters needs to be sent as form url encoded body
Update 2
Value of R.Api.headers is
["Content-Type" : "application/x-www-form-urlencoded"]
If you want to send request as a form-urlencoded, you should put it as a headers and change your encoding:
let headers = [
"Content-Type": "application/x-www-form-urlencoded"
]
var params = [
"username": "jora#company.com",
"password": "test123",
"pushToken": "No token"
]
Alamofire.request("your_url_here", method: .post, parameters: parameters, encoding: URLEncoding.httpBody, headers: headers).responseJSON { response in
}
The backend was an IIS server with redirection to Tomcat. I've excluded IIS and make the requests directly to Tomcat and it is working now. As I understood, the problem was in delivering the request from IIS to Tomcat.
Solved

{ error = "invalid_request"; "error_description" = "Required parameter is missing: grant_type"; } In swift

I am trying with this but every time I will get
{ error = "invalid_request"; "error_description" = "Required parameter is missing: grant_type"; }
Request String:
let headers = [ "Content-Type" : "application/x-www-form-urlencoded"]
let urlString = "https://accounts.google.com/o/oauth2/token?"
Alamofire.request(urlString, method: .post, parameters: ["grant_type":"authorization_code","code":"4/FAOYR1mQo1lN1Gdg9jDnigwZ8RP76NUrqPbYZlMCSP28","client_id":"387376833747-12pbtud9tepr4di0insdhc0d4qpf5e9m.apps.googleusercontent.com","client_secret":"xOacVhLavM9fH8SpOK4I2dRJ","redirect_uri":"https://stackoverflow.com"], encoding: JSONEncoding.default, headers : headers)
.responseJSON { response in
print(response)
print(response.result)
}
Also try with passing request parameter like this but still doesn't work for me.
You can't send appended parameter with url while post request.
Pass parameter as below this
let headers = [ "Content-Type" : "application/x-www-form-urlencoded","grant_type" : "authorization_code"" ]
let urlString = "https://accounts.google.com/o/oauth2/token?"
Alamofire.request(urlString, method: .post, parameters: ["code":"4/FAOYR1mQo1lN1Gdg9jDnigwZ8RP76NUrqPbYZlMCSP28","client_id":"apps.googleusercontent.com","client_secret":"","redirect_uri":"https://stackoverflow.com"], encoding: JSONEncoding.default, headers : headers)
.responseJSON { response in
print(response)
print(response.result)
}
These error invalid_request occurs only below cases so please check with your server side what is missing or invalid.
The request is missing a required parameter, includes an unsupported
or invalid parameter value, repeats a parameter,includes multiple
credentials, utilizes more than one mechanism for authenticating the
client, or is otherwise malformed.

How to pass Token Key and Token Secret to Alamofire request?

I have Consumer Key, Consumer Secret, Token Key and Token Secret to get Data API. like this in postman:
I must get data my API like in capture postman above. then I have method request with Alamofire like this:
Alamofire.request("https://conversation.8villages.com/1.0/contents/articles?state=published", headers: headers).responseJSON { response in
print("test", response.request!) // original URL request
print("ini responseny", response.response!) // HTTP URL response
print("test", response.data!) // server data
print("test", response.result) // result of response serialization
if let JSON = response.result.value {
print("JSON: \(JSON)")
}
}
So, I don't know how to add or pass my token to in method get. someone help me, please.
I'm using OAuthSwift and Alamofire.
Try this
let headers: HTTPHeaders = [
"Authorization": "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==",
"Accept": "application/json"
]
Alamofire.request("https://httpbin.org/headers", headers: headers).responseJSON { response in
debugPrint(response)
}

Alamofire 4.3 can't send JSON request

Iam Trying to send a JSON request using Alamofire but it's not working as a JSON Request here's my JSON :
{"ClientID":"55050","AdminId":"myemail","Password":"123"}
content-type → application/json; charset=utf-8
and here's my code :
import Alamofire
func doLogin(username:String ,password:String) {
let parameters = ["ClientID":"55050" , "AdminId":username,"Password":password]
Alamofire.request("myurl.com", method: .post, parameters: parameters, encoding: JSONEncoding(options: []) ).responseJSON(completionHandler: {
response in
print(response)
})
and here's the response which i am getting
FAILURE: responseSerializationFailed(Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 3." UserInfo={NSDebugDescription=Invalid value around character 3.}))
By reading the documentation i just need to put header to set the request as application/json
so i added extra parameter header :
let headers: HTTPHeaders = [
"Authorization": "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==",
"Accept": "application/json"
]
Alamofire.request(ApiKeys().login, method : .post , parameters : parameters, encoding: JSONEncoding.default , headers: headers).responseJSON { response in
}
and now it's working perfectly thanks everyone for trying to help :)
It seems you must have missed header in your request. So, there has been no response.
Your header must be a dictionary [String: String].
let header = ["Content-Type" : "application/json"]
And your sample request should be:
Alamofire.request(getCategoryPath, method: .post, parameters: parameters, encoding: URLEncoding.default, headers: header)
.responseJSON { response in
guard response.result.error == nil else {
print(response.result.error!)
}
print(response.result.value)
}

Resources