我正在研究twitter api,其中一些api得到了回应。但是statuses/home_timeline.json
API和其他API没有得到响应。
出错:
{"errors":[{"code":220,"message":"Your credentials do not allow access to this resource."}]}
我成功获取访问令牌,并将该访问令牌用于statuses/home_timeline.json
和其他一些api。但是这些都超过了错误。我已经用我的帐户登录了。
我发现了很多网址,但我没有从这些网址得到答案。
我的访问令牌代码是:
//Get twitter access token
func getAccessToken() {
//RFC encoding of ConsumerKey and ConsumerSecretKey
let encodedConsumerKeyString:String = "f4k***********0".addingPercentEncoding(withAllowedCharacters: CharacterSet.urlHostAllowed)!
let encodedConsumerSecretKeyString:String = "OD**************ln".addingPercentEncoding(withAllowedCharacters: CharacterSet.urlHostAllowed)!
print(encodedConsumerKeyString)
print(encodedConsumerSecretKeyString)
//Combine both encodedConsumerKeyString & encodedConsumerSecretKeyString with " : "
let combinedString = encodedConsumerKeyString+":"+encodedConsumerSecretKeyString
print(combinedString)
//Base64 encoding
let data = combinedString.data(using: .utf8)
let encodingString = "Basic "+(data?.base64EncodedString())!
print(encodingString)
//Create URL request
var request = URLRequest(url: URL(string: "https://api.twitter.com/oauth2/token")!) //oauth/access_token oauth2/token
request.httpMethod = "POST"
request.setValue(encodingString, forHTTPHeaderField: "Authorization")
request.setValue("application/x-www-form-urlencoded;charset=UTF-8", forHTTPHeaderField: "Content-Type")
let bodyData = "grant_type=client_credentials".data(using: .utf8)!
request.setValue("\(bodyData.count)", forHTTPHeaderField: "Content-Length")
request.httpBody = bodyData
let task = URLSession.shared.dataTask(with: request) { data, response, error in guard let data = data, error == nil else { // check for fundamental networking error
print("error=\(String(describing: error))")
return
}
// let responseString = String(data: data, encoding: .utf8)
// let dictionary = data
// print("dictionary = \(dictionary)")
// print("responseString = \(String(describing: responseString!))")
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { // check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(String(describing: response))")
}
do {
let response = try JSONSerialization.jsonObject(with: data, options: []) as! Dictionary<String, Any>
print("Access Token response : \(response)")
// print(response["access_token"]!)
// self.accessToken = response["access_token"] as! String
if let token = response["access_token"] {
self.accessToken = token as! String
}
} catch let error as NSError {
print(error)
}
}
task.resume()
}
Twitter 签名代码:
//Twitter signin
@IBAction func onClickTwitterSignin(_ sender: UIButton) {
//Login and get session
TWTRTwitter.sharedInstance().logIn { (session, error) in
if (session != nil) {
//Read data
let name = session?.userName ?? ""
print(name)
print(session?.userID ?? "")
print(session?.authToken ?? "")
print(session?.authTokenSecret ?? "")
// self.loadFollowers(userid: session?.userID ?? "")
// let userid = session?.userID ?? ""
// let screenName = session?.userName ?? ""
// if userid != "" && screenName != "" {
self.getStatusesUserTimeline(accessToken:self.accessToken)
// }
//Get user email id
let client = TWTRAPIClient.withCurrentUser()
client.requestEmail { email, error in
if (email != nil) {
let recivedEmailID = email ?? ""
print(recivedEmailID)
} else {
print("error--: \(String(describing: error?.localizedDescription))");
}
}
//Get user profile image url's and screen name
let twitterClient = TWTRAPIClient(userID: session?.userID)
twitterClient.loadUser(withID: session?.userID ?? "") { (user, error) in
print(user?.profileImageURL ?? "")
print(user?.profileImageLargeURL ?? "")
print(user?.screenName ?? "")
}
let storyboard = self.storyboard?.instantiateViewController(withIdentifier: "SVC") as! SecondViewController
self.navigationController?.pushViewController(storyboard, animated: true)
} else {
print("error: \(String(describing: error?.localizedDescription))");
}
}
}
获取twitter statuses / home_timeline.json:(登录成功后我将调用此函数)
func getStatusesUserTimeline(accessToken:String) {
let userId = "10************56"
let twitterClient = TWTRAPIClient(userID: userId)
twitterClient.loadUser(withID: userId) { (user, error) in
print(userId)
print(user ?? "Empty user")
if user != nil {
//Get users timeline tweets
var request = URLRequest(url: URL(string: "https://api.twitter.com/1.1/statuses/home_timeline.json?")!)
request.httpMethod = "GET"
request.setValue("Bearer "+accessToken, forHTTPHeaderField: "Authorization")
print(request)
let task = URLSession.shared.dataTask(with: request) { data, response, error in guard let data = data, error == nil else { // check for fundamental networking error
print("error=\(String(describing: error))")
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { // check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(String(describing: response))")
}
do {
let response = try JSONSerialization.jsonObject(with: data, options: []) as! Dictionary<String,Any>
print(response)
// print((response["statuses"] as! Array<Any>).count)
} catch let error as NSError {
print(error)
}
}
task.resume()
} else {
print(error?.localizedDescription as Any)
}
}
}