Get twitter friends list?
In Swift 4.2, Xcode 10.1 and iOS 12.1
Finally i got the solution for this. Here first we need Authorisation then need to implement friends list api.
Pure Swift code is not available. But i implemented in pure swift.
If you want to get friends/list data from twitter you need to use two API's.
1) oauth2/token API
2) friends/list API
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) First use oauth2/token api for access token.
2) After getting access token use twitter login api for user id and screen name.
3) Now use friends/list api.
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) Get access token code (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()
}
Output :
{"token_type":"bearer","access_token":"AAAAAAAAAAAAAAAAAAA............xqT3t8T"}
2) Login with twitter code
@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))");
}
}
}
Output:
Here you will get userName, userId, authtoken, authTokenSecret, screen name and email etc.
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.
How to get Twitter Friends List?
Use this library, you can easily achieve that
https://www.temboo.com/library/Library/Twitter/FriendsAndFollowers/GetFriendsByID/
and you need set authorization before you connect. just go through this Documentation
https://dev.twitter.com/docs/auth/authorizing-request
and this post will help you how to implement to get the friendlist go to this list read those codes
In Android -How directly post tweet to following users of a authenticate user in android without open Tweet dialog (Message Dialog box)
Full list of twitter friends using python and tweepy
According to the source code, friends()
is referred to the GET friends / list
twitter endpoint, which allows a count
parameter to be passed in:
The number of users to return per page, up to a maximum of 200. Defaults to 20.
This would allow you to get 200 friends via friends()
.
Or, better approach would be to use a Cursor
which is a paginated way to get all of the friends:
for friend in tweepy.Cursor(api.friends).items():
# Process the friend here
process_friend(friend)
See also:
- incomplete friends list
- Tweepy Cursor vs Iterative for low API calls
How to get list of all twitter followers using twitter4j?
Just Change like this and try, this is working for me
try {
Log.i("act twitter...........", "ModifiedCustomTabBarActivity.class");
// final JSONArray twitterFriendsIDsJsonArray = new JSONArray();
IDs ids = mTwitter.mTwitter.getFriendsIDs(-1);// ids
// for (long id : ids.getIDs()) {
do {
for (long id : ids.getIDs()) {
String ID = "followers ID #" + id;
String[] firstname = ID.split("#");
String first_Name = firstname[0];
String Id = firstname[1];
Log.i("split...........", first_Name + Id);
String Name = mTwitter.mTwitter.showUser(id).getName();
String screenname = mTwitter.mTwitter.showUser(id).getScreenName();
// Log.i("id.......", "followers ID #" + id);
// Log.i("Name..", mTwitter.mTwitter.showUser(id).getName());
// Log.i("Screen_Name...", mTwitter.mTwitter.showUser(id).getScreenName());
// Log.i("image...", mTwitter.mTwitter.showUser(id).getProfileImageURL());
}
} while (ids.hasNext());
} catch (Exception e) {
e.printStackTrace();
}
How to get the Twitter followers count using Twitter API (in 2022)?
Yes, there is a simple way to do this using the Twitter API v2!
The follower and following counts for a user are part of the public_metrics
fields in the User object.
The API endpoint and parameters are in the format
https://api.twitter.com/2/users/[ID]?user.fields=public_metrics,[any other fields]
Here's an example of the output, using the twurl
command line tool (which handles the authentication etc, you may need to use a library to help with OAuth):
$ twurl -j "/2/users/786491?user.fields=public_metrics,created_at"
{
"data": {
"id": "786491",
"username": "andypiper",
"created_at": "2007-02-21T15:14:48.000Z",
"name": "andypiper.xyz",
"public_metrics": {
"followers_count": 16570,
"following_count": 3247,
"tweet_count": 134651,
"listed_count": 826
}
}
}
Related Topics
Unexpected Non-Void Return Value in Void Function Swift3
Changing Placeholder Text Color with Swift
How to Create a Simple Checkbox in iOS
Enterprise In-House App Distribution
Cocoapods Not Installed or Not in Valid State
Changed Project Name in Xcode Causing Naming Error
Using Ldap for Authentication in iOS
Expand Uilabel Inside Uitableview with "More" Button Like Instagram
Firebase Cloud Messaging Doesn't Create Push Notifications But Gets Information
Write Extend File Attributes Swift Example
Automatically Adjustable View Height Based on Text Height in Swiftui
Getting Time Elapsed in Objective-C
iOS Autolayout with Uiscrollview: Why Does Content View of Scroll View Not Fill the Scroll View
Implementing Google Custom Search API in iOS
How to Convert an Int to Hex String in Swift
Waiting for Multiple Asynchronous Download Tasks
Send Programmatically Sms on Jailbreak Device
Xcode - Mpnowplayinginfocenter Info Is Not Displayed on iOS 8