我正在尝试创建TwitterSearcher。
我的条件是
正如你们中的一些人所知,你需要获得一个令牌才能在搜索推文之前访问Twitter。
我对使用API本身很陌生,但我几乎没有实现一些代码。但是,我在获取令牌的方式上遇到了错误响应。
{
"errors" : [
{
"code" : 170,
"label" : "forbidden_missing_parameter",
"message" : "Missing required parameter: grant_type"
}
]
}
我已经尝试过某些方式来引用其他文章,比方说
虽然我没有抓住这两个意思,但错误仍在继续。
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")
}
}
希望你们能帮助我。
您可以尝试使用URLEncoding.httpBody
而不是JSONEncoding.default
要么
Alamofire直接支持Basic auth
看到这个
https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#authentication
以下是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)
}
并使用authorizationHeader
作为alamofire中的请求标头
希望它有所帮助