获取推特好友列表? [英] Get twitter friends list?

查看:26
本文介绍了获取推特好友列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Twitter 好友/列表 API 中收到 Bad Authentication data 响应.我在登录时获取用户 ID、屏幕名称、authToken 和 authTokenSecret.

I'm getting Bad Authentication data response in twitter friends/list API. I'm getting userid, screen name, authToken and authTokenSecret when login.

func loadFollowers(userid:String) {

    //let twapi = "https://api.twitter.com/1.1/followers/list.json?cursor=-1&user_id=(session)&count=5000"
    let twapi = "https://api.twitter.com/1.1/friends/list.json?cursor=-1&user_id=(userid)&count=10"
    let url2 = URL(string: twapi)!
    print(url2)
    URLSession.shared.dataTask(with: url2, completionHandler: { (data, response, error) in

    //UIApplication.shared.isNetworkActivityIndicatorVisible = false
        do {
            let userData = try JSONSerialization.jsonObject(with: data!, options:[])
            print(userData)
        } catch {
            NSLog("Account Information could not be loaded (error)")
        }
    }).resume()
}

输出:

{
"errors": [
    {
        "code": 215,
        "message": "Bad Authentication data."
    }
]
}

friends/list.json API 中需要发送哪些参数.在本文档中,他们给出的所有参数都是可选的.https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friends-list

What are the required parameters to send in friends/list.json API. In this document they given all parameters are optional. https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friends-list

推荐答案

在 Swift 4.2、Xcode 10.1 和 iOS 12.1 中

In Swift 4.2, Xcode 10.1 and iOS 12.1

我终于找到了解决方案.这里首先需要Authorization,然后需要实现好友列表api.

Finally i got the solution for this. Here first we need Authorisation then need to implement friends list api.

纯 Swift 代码不可用.但我是用纯粹的 swift 实现的.

Pure Swift code is not available. But i implemented in pure swift.

如果您想从 Twitter 获取朋友/列表数据,您需要使用两个 API.

If you want to get friends/list data from twitter you need to use two API's.

1) oauth2/token API

2) 好友/列表 API

oauth2/token api 中你可以获得访问令牌,因为你需要访问令牌来访问好友列表.并且您需要用户 ID、屏幕名称.

In oauth2/token api you can get access token, because you need access token for friends list. And you need user id, screen name.

但是在这里您必须记住一个重要的点.

But here you must remember one important point.

1) 首先使用 oauth2/token api 作为访问令牌.

1) First use oauth2/token api for access token.

2) 获得访问令牌后,使用 twitter login api 作为 用户 ID 和屏幕名称.

2) After getting access token use twitter login api for user id and screen name.

3) 现在使用 friends/list api.

3) Now use friends/list api.

在这里,如果您首先使用 twitter 登录,然后使用 oauth2/token api 作为访问令牌,您可能会遇到 Bad Authentication data 错误.所以请您按顺序执行以上 3 个步骤.

Here first if you use twitter login then oauth2/token api for access token, you can get like Bad Authentication data error. So you please follow above 3 steps in order.

1) 获取访问令牌代码(oauth2/token api):

func getAccessToken() {

    //RFC encoding of ConsumerKey and ConsumerSecretKey
    let encodedConsumerKeyString:String = "sx5r...S9QRw".addingPercentEncoding(withAllowedCharacters: CharacterSet.urlHostAllowed)!
    let encodedConsumerSecretKeyString:String = "KpaSpSt.....tZVGhY".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")!)
    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

            self.getStatusesUserTimeline(accessToken:self.accessToken)

        } catch let error as NSError {
            print(error)
        }
    }

    task.resume()
}

输出:

{"token_type":"bearer","access_token":"AAAAAAAAAAAAAAAAAAA............xqT3t8T"}

2) 使用推特代码登录

@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 ?? "")

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

}

输出:

在这里您将获得用户名、用户 ID、身份验证令牌、身份验证令牌秘密、屏幕名称和电子邮件等.

Here you will get userName, userId, authtoken, authTokenSecret, screen name and email etc.

3) 现在从朋友/列表 api 获取朋友列表.在这里您可以获取好友/列表、用户/查找、关注者/ID、关注者/列表 api 的数据等...

3) Now get friends list from friends/list api. Here you can get friends/list, users/lookup, followers/ids, followers/list api's data etc...

func getStatusesUserTimeline(accessToken:String) {

    let userId = "109....456"
    let twitterClient = TWTRAPIClient(userID: userId)
    twitterClient.loadUser(withID: userId) { (user, error) in
        if user != nil {
            //Get users timeline tweets
            var request = URLRequest(url: URL(string: "https://api.twitter.com/1.1/friends/list.json?screen_name=KS....80&count=10")!) //users/lookup, followers/ids, followers/list 
            request.httpMethod = "GET"
            request.setValue("Bearer "+accessToken, forHTTPHeaderField: "Authorization")

            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: [])
                    print(response)

                } catch let error as NSError {
                    print(error)
                }
            }

            task.resume()

        }
    }

}

此代码在任何地方都不可用.我为这段代码尝试了很多,为此我花了很多时间.谢谢.

This code not available any where. I tried a lot for this code and i spent lot of time for this. Thank you.

这篇关于获取推特好友列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆