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

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

Related

Client Credentials Flow - getting access token

How can I receive an access_token through Client Credentials Flow to Spotify by using Alamofire?
Here is my code so far:
// Spotify API
func callAlamo(url: String) {
let parameters = ["client_id" : "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
"client_secret" : "yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy",
"grant_type" : "client_credentials"]
let headers = ["Authorization" : "Basic xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"] // <- xxx is the client_id
Alamofire.request("https://accounts.spotify.com/api/token", method: .post, parameters: parameters, headers: headers).responseJSON(completionHandler: {
response in
print(response.result)
print(response.result.value)
})
}
Here is a section of my print log:
SUCCESS
Optional({
error = "invalid_client";
})
What is wrong with this code? Am I sending the wrong parameters or headers? Did I forget something?
Note: The client_id and client_secret are correct
- If there is anything unclear, please message me -
After multiple days and 2 questions later, I figured it out myself. It was an extremely simple fix, which is frustrating.
All I did was delete the headers parameter in the request.
Another option is that you can set headers to nil.
Alamofire.request("https://accounts.spotify.com/api/token", method: .post, parameters: parameters).responseJSON(completionHandler: {
response in
print(response.result)
print(response.result.value)
})
Well I don't know how this is working.
In theory, the correct execution is:
- Make a POST request to url:
https://accounts.spotify.com/api/token
set as headers:
"Content-Type": "application/x-www-form-urlencoded"
"Authorization": "Basic xxxxx"
Where xxxxx is the base64 encoded string of client_id:client_secret (so client_id string and client_secret separated by :)
set as body:
"grant_type": "client_credentials"
This will give you the correct response
eg.
{
"access_token": "BQCJeyp3ocQZzSksvNn3IXuvY0NsYI26YMF400jp-7Dd8zGz6ecXyywwmSdy4jrPWwLZA_6l4e59lu8dYfg",
"token_type": "Bearer",
"expires_in": 3600,
"scope": ""
}

Swift Alamofire Getting Token from Refresh Token Request Error

I'm pretty new to using Alamofire, and I am banging my head against the wall with this request. I'm using GIDSignIn, and successfully get a token and refresh token for the user, with the scope ["https://www.googleapis.com/auth/youtube.readonly"].
I'm trying to complete this request, as shown as an example on the site. The site says to ignore using client_secret for iOS, which I do.
POST /oauth2/v4/token HTTP/1.1
Host: www.googleapis.com
Content-Type: application/x-www-form-urlencoded
client_id=<your_client_id>&
client_secret=<your_client_secret>&
refresh_token=<refresh_token>&
grant_type=refresh_token
Below is how I've implemented it with Alamofire. My client_id is the value from the CLIENT_ID key in the GoogleService-Info.Plist, a string ending in .apps.googleusercontent.com. The refresh_token also seems to have the right format from other examples I've seen online.
let endpoint = "https://www.googleapis.com/oauth2/v4/token"
let parameters = [
"client_id" : client_id,
"refresh_token" : refresh_token,
"grant_type" : "refresh_token"
]
Alamofire.request(endpoint, method: .post,
parameters: parameters,
encoding: JSONEncoding.default)
.responseJSON { (data) in
print("data: \(data)")
let json = JSON(data.result)
}
The data response is
data: SUCCESS: {
error = "unsupported_grant_type";
"error_description" = "Invalid grant_type: ";
}
Not terribly successful. Do I need to configure my request differently, or get appropriate access / permission to get the token? Thank you so much!
#BikeshThakur helped me figure it out! The URLEncoding.httpBody did the trick! I don't need any headers either.
Alamofire.request(endpoint, method: .post,
parameters: parameters,
encoding: URLEncoding.httpBody)
i have tired in my code like this way , you also need to check sometime encoding type URLEncoding.httpBody hope it may help
let headers = [
"Content-Type": "application/x-www-form-urlencoded"
]
Alamofire.request("https://accounts.google.com/o/oauth2/revoke?token={\(token)}", method: .post, parameters: parameters, encoding: URLEncoding.httpBody, headers: headers).responseJSON { (response:DataResponse<Any>) in

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

Twitter API in SWIFT via Alamofire

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.

Alamofire POST route returning data

So I am trying to POST to my API on my iPhone app. When I POST I want to be able to return a struct that has data. How would I do that? So far I have
Alamofire.request(.POST, "API_URL", parameters)
Is there some way to store what the API gives back?
Try using this
Alamofire.request(.POST, "API_URL, parameters).responseJSON{ request, response, result in
print(result.value)
}
If you want to use the resulting JSON in an easy manner - I would suggest using SWIFTY JSON
Yes you can.If you are using the latest version of Alamofire.
Simply try this(If the returning data is in JSON)
let url1 = "http://yoururl.com"
let head = [ "Accept": "application/json;charset=UTF-8",
"Content-Type": "application/json;charset=UTF-8"] // Adding headers
let p = ["Email":"anything","Password": "123"] // Adding parameters if any
Alamofire.request(.POST,url1, parameters: p, encoding : .JSON, headers : head)
.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
}

Resources