Twitter错误:您的凭据不允许访问此资源

问题描述 投票:4回答:1

我正在研究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。但这些都超过了错误。我已经使用我的帐户登录了。

我找到了这么多网址,但我没有得到那些网址的答案。

我的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状态/ 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)
        }
    }

}
ios swift twitter oauth twitter-oauth
1个回答
2
投票

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

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

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

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.