I'm attempting to create TwitterSearcher.
My Conditions are
As some of you know, you need to get a token in order to access Twitter before searching for tweets.
I'm pretty new to using API itself but I barely implemented some code. However, I came across an error response below on the way to get a token.
{
"errors" : [
{
"code" : 170,
"label" : "forbidden_missing_parameter",
"message" : "Missing required parameter: grant_type"
}
]
}
I have already tried some ways referring to other articles, let's say
Although I haven't grabbed the meanings of these two, the error is still going on.
import Foundation
import Alamofire
import SwiftyJSON
protocol SearchUserApi {
func getToken()
func getTweets(content: String)
}
class APIOperator: SearchUserApi {
var accessToken: String?
let tokenApi = "https://api.twitter.com/oauth2/token"
let api = "https://api.twitter.com/1.1/search/tweets.json"
let consumerKey = "---"
let consumerSecret = "---"
func getToken() {
let credentials = "\(consumerKey):\(consumerSecret)".data(using: String.Encoding.utf8)!.base64EncodedString(options: NSData.Base64EncodingOptions(rawValue: 0))
let headers = [
"Authorization" : "Basic \(credentials)",
"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8"
]
let params: [String : AnyObject] = ["grant_type": "client_credentials" as AnyObject]
Alamofire.request(
tokenApi,
method: .post,
parameters: params,
encoding: JSONEncoding.default,
headers: headers
)
.responseJSON { (response) in
guard let object = response.result.value else {
print("Getting token is failed")
return
}
let json = JSON(object)
print(json)
}
}
func getTweets(content: String) {
print("not yet")
}
}
Hope you will help me out.
You can try with URLEncoding.httpBody
instead of JSONEncoding.default
OR
Alamofire directly support Basic auth
see this
https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#authentication
Here is sample code from docs
let user = "user"
let password = "password"
let credential = URLCredential(user: user, password: password, persistence: .forSession)
Alamofire.request("https://httpbin.org/basic-auth/\(user)/\(password)")
.authenticate(usingCredential: credential)
.responseJSON { response in
debugPrint(response)
}
and use authorizationHeader
as request header in alamofire
Hope it is helpful