我正在尝试创建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")
}
}
希望你们会帮助我。
答案 0 :(得分:0)
您可以尝试使用URLEncoding.httpBody
代替JSONEncoding.default
OR
Alamofire直接支持基本身份验证
查看此
https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#authentication
这是来自文档的示例代码
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中的请求标头
希望对您有帮助