问题
I'm working on twitter api's, some of api's getting response. But statuses/home_timeline.json
api and other api's not getting response.
Getting error :
{"errors":[{"code":220,"message":"Your credentials do not allow access to this resource."}]}
I'm getting access token successfully and using that access token for statuses/home_timeline.json
and some other api's. But these are getting above error. Already i logged in with my account.
I found so many urls and i'm not getting answer from those urls.
My Accesstoken code is:
//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 signing code :
//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))");
}
}
}
Get twitter statuses/home_timeline.json : (I'm calling this function after login success)
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)
}
}
}
回答1:
Check permission as follow screenshot. Goto developer account -> Dashboard -> select your app -> Permissions.
Would it be the case that you are using app-only authentication, or an app which has only read-only permissions?
Please make sure your app has a read-write access OR Read, write, and direct messages access
来源:https://stackoverflow.com/questions/55373430/your-credentials-do-not-allow-access-to-this-resource-twitter-api-error