我正在尝试创建TwitterSearcher。
我的条件是
- 使用仅限应用的身份验证
- 标准搜索接口
- 使用Alamofire,SwiftyJSON
正如你们中的一些人所知,在搜索推文之前,您需要获得令牌才能访问Twitter。
我对使用 API 本身很陌生,但我几乎没有实现一些代码。但是,我在获取令牌的途中遇到了下面的错误响应。
{
"errors" : [
{
"code" : 170,
"label" : "forbidden_missing_parameter",
"message" : "Missing required parameter: grant_type"
}
]
}
我已经尝试了一些参考其他文章的方法,比方说
- 将参数更改为 ["有效负载" : "grant_type=client_credentials"]
- 从标题中删除"content_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直接支持基本身份验证
看到这里
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)
}
并在 Alamofire 中使用 authorizationHeader
作为请求标头
希望对您有所帮助