2
我想使用應用程序唯一身份驗證進行身份驗證,並且我成功獲取不記名令牌,但是當我嘗試調用REST API時,我總是收到401錯誤,這是我的代碼:Twitter只有應用程序驗證總是返回401
private var accessToken: String?
private let consumerKey = "*********"
private let consumerSecret = "*********"
private let baseUrlString = "https://api.twitter.com/1.1/"
private let pageSize = 20
private func authenticate(completionBlock: Void ->()) {
if accessToken != nil {
completionBlock()
}
let credentials = "\(consumerKey):\(consumerSecret)"
let headers = ["Authorization": "Basic \(credentials.getBase64())"]
let params: [String : AnyObject] = ["grant_type": "client_credentials"]
Alamofire.request(.POST, "https://api.twitter.com/oauth2/token", headers: headers, parameters: params)
.responseJSON { response in
if let JSON = response.result.value {
self.accessToken = JSON.objectForKey("access_token") as? String
completionBlock()
}
}
}
func getTimelineForScreenName(screenName: String) {
authenticate {
guard let token = self.accessToken else {
// TODO: Show authentication error
return
}
let headers = ["Authorization": "Bearer \(token.getBase64())"]
let params: [String : AnyObject] = [
"screen_name" : screenName,
"count": self.pageSize
]
Alamofire.request(.GET, self.baseUrlString + "statuses/user_timeline.json", headers: headers, parameters: params)
.responseJSON { response in
print(response.response)
if let JSON = response.result.value {
print(JSON)
}
}
}
}
...
private extension String {
func getBase64() -> String {
let credentialData = self.dataUsingEncoding(NSUTF8StringEncoding)!
return credentialData.base64EncodedStringWithOptions([])
}
}
我試圖創造新的密鑰,但什麼都沒有,也嘗試過什麼建議在iOS版9不讓Authorization
頭髮現這個錯誤的導向,但這一請求獲得通過沒有使用任何重定向。
任何想法將不勝感激。
你能接受你的答案嗎? –
@RhythmicFistman我試過了,但說明天后我可以接受。 –
好的,沒問題。我喜歡看到案件結案。 –