ios - 您的凭据不允许访问此资源 Twitter API 错误

标签 ios swift twitter oauth twitter-oauth

我正在开发 Twitter API,其中一些 API 正在获得响应。但是 statuses/home_timeline.json api 和其他 api 没有得到响应。

获取错误:

{"errors":[{"code":220,"message":"Your credentials do not allow access to this resource."}]}

我正在成功获取访问 token 并将该访问 token 用于 statuses/home_timeline.json 和其他一些 api。但是这些都超出了错误。我已经用我的帐户登录了。

我找到了很多网址,但我没有从这些网址中得到答案。

我的Accesstoken代码是:

//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)
        }
    }

}

最佳答案

检查权限如下截图。转到开发者帐户 -> 仪表板 -> 选择您的应用 -> 权限。

您使用的是仅应用程序身份验证,还是仅具有只读权限的应用程序?

请确保您的应用具有读写访问权限或读取、写入和直接消息访问权限

enter image description here

关于ios - 您的凭据不允许访问此资源 Twitter API 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55373430/

相关文章:

oauth - 使用 OAuth 签署 twitter 用户流请求

ios - 使用超链接集成 UPI 后如何获得响应

objective-c - 让 GADInterstitialAd 在 iPad 上更频繁地加载 : possible?

iOS UICollectionView : Cells with circular view in alternating grid alignment

ios - viewDidLoad 中的变量未填充自定义表格单元格

ruby-on-rails - Twitter 卡片验证器在开发时出现错误

html - 停止官方 twitter 小部件逃出我的 div 边界

ios - 正确更新 NSManagedObject 关系

ios - 隐藏基于 TableView 选择的 UILabel

ios - 在 Swift 中创建带参数的线程?