Get Twitter Followers and following in ios7 - ios

i have used Twitter API to get followers and following.
i have write this code. to get followers and following
-(void)getTwitterAccounts
{
ACAccountStore *accountStore = [[ACAccountStore alloc] init];
// Create an account type that ensures Twitter accounts are retrieved.
ACAccountType *accountType = [accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];
// let's request access and fetch the accounts
[accountStore requestAccessToAccountsWithType:accountType
withCompletionHandler:^(BOOL granted, NSError *error)
{
// check that the user granted us access and there were no errors (such as no accounts added on the users device)
if (granted && !error)
{
NSArray *accountsArray = [accountStore accountsWithAccountType:accountType];
if ([accountsArray count] > 1) {
// a user may have one or more accounts added to their device
// you need to either show a prompt or a separate view to have a user select the account(s) you need to get the followers and friends for
} else {
[self getTwitterFriendsForAccount:[accountsArray objectAtIndex:0]];
}
} else {
// handle error (show alert with information that the user has not granted your app access, etc.)
}
}];
}
-(void)getTwitterFriendsForAccount:(ACAccount*)account
{
// In this case I am creating a dictionary for the account
// Add the account screen name
NSMutableDictionary *accountDictionary = [NSMutableDictionary dictionaryWithObjectsAndKeys:account.username, #"screen_name", nil];
// Add the user id (I needed it in my case, but it's not necessary for doing the requests)
[accountDictionary setObject:[[[account dictionaryWithValuesForKeys:[NSArray arrayWithObject:#"properties"]] objectForKey:#"properties"] objectForKey:#"user_id"] forKey:#"user_id"];
// Setup the URL, as you can see it's just Twitter's own API url scheme. In this case we want to receive it in JSON
NSURL *followingURL = [NSURL URLWithString:#"http://api.twitter.com/1/friends/ids.json"];
// Pass in the parameters (basically '.ids.json?screen_name=[screen_name]')
NSDictionary *parameters = [NSDictionary dictionaryWithObjectsAndKeys:account.username, #"screen_name", nil];
// Setup the request
TWRequest *twitterRequest = [[TWRequest alloc] initWithURL:followingURL
parameters:parameters
requestMethod:TWRequestMethodGET];
// This is important! Set the account for the request so we can do an authenticated request. Without this you cannot get the followers for private accounts and Twitter may also return an error if you're doing too many requests
[twitterRequest setAccount:account];
// Perform the request for Twitter friends
[twitterRequest performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) {
if (error) {
// deal with any errors - keep in mind, though you may receive a valid response that contains an error, so you may want to look at the response and ensure no 'error:' key is present in the dictionary
}
NSError *jsonError = nil;
// Convert the response into a dictionary
NSDictionary *twitterFriends = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableLeaves error:&jsonError];
// Grab the Ids that Twitter returned and add them to the dictionary we created earlier
[accountDictionary setObject:[twitterFriends objectForKey:#"ids"] forKey:#"friends_ids"];
NSLog(#"%#", accountDictionary);
}];
}
but this code not works
give me error
NSRangeException', reason: '* -[__NSArrayI objectAtIndex:]: index 0 beyond bounds for empty array'**
why this is happening. please help me to sort out this.

Finally i get the solution.
Here is the Solution for get the Twitter Followers and Following Names
First you need to get the Valid Username. and that name you can get it from
this code.
NSString * username = [FHSTwitterEngine sharedEngine].authenticatedUsername;
using that username you can get whatever you want
NSMutableDictionary * dict1 = [[FHSTwitterEngine sharedEngine]listFriendsForUser:username isID:NO withCursor:#"-1"];
NSLog(#"====> %#",[dict1 objectForKey:#"users"] ); // Here You get all the data
NSMutableArray *array=[dict1 objectForKey:#"users"];
for(int i=0;i<[array count];i++)
{
NSLog(#"names:%#",[[array objectAtIndex:i]objectForKey:#"name"]);
}

Try this. Looks like you were trying to use old twitter api
ACAccountStore *accountStore = [[ACAccountStore alloc] init];
ACAccountType *accountType = [accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];
[accountStore requestAccessToAccountsWithType:accountType options:nil completion:^(BOOL granted, NSError *error){
if (granted) {
NSArray *accounts = [accountStore accountsWithAccountType:accountType];
// Check if the users has setup at least one Twitter account
if (accounts.count > 0)
{
ACAccount *twitterAccount = [accounts objectAtIndex:0];
for(ACAccount *t in accounts)
{
if([t.username isEqualToString:username])
{
twitterAccount = t;
break;
}
}
SLRequest *twitterInfoRequest = [SLRequest requestForServiceType:SLServiceTypeTwitter requestMethod:SLRequestMethodGET URL:[NSURL URLWithString:#"https://api.twitter.com/1.1/friends/ids.json?"] parameters:[NSDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:#"%#", username], #"screen_name", #"-1", #"cursor", nil]];
[twitterInfoRequest setAccount:twitterAccount];
// Making the request
[twitterInfoRequest performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) {
dispatch_async(dispatch_get_main_queue(), ^{
// Check if we reached the reate limit
if ([urlResponse statusCode] == 429) {
NSLog(#"Rate limit reached");
return;
}
// Check if there was an error
if (error) {
NSLog(#"Error: %#", error.localizedDescription);
return;
}
// Check if there is some response data
if (responseData) {
NSError *error = nil;
NSArray *TWData = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableLeaves error:&error];
}
});
}];
}
} else {
NSLog(#"No access granted");
}
}];

Related

How to get followers and following with Twitter/Social framework in iOS

How can I get all followers and following from a user's Twitter account.
I get followers and following counts. However I need usernames of followers and following users.
Here my code.
- (void) getAccountInfo
{
ACAccountStore *accountStore = [[ACAccountStore alloc] init];
ACAccountType *accountType = [accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];
[accountStore requestAccessToAccountsWithType:accountType options:nil completion:^(BOOL granted, NSError *error){
if (granted) {
NSArray *accounts = [accountStore accountsWithAccountType:accountType];
// Check if the users has setup at least one Twitter account
if (accounts.count > 0)
{
ACAccount *twitterAccount = [accounts objectAtIndex:0];
// Creating a request to get the info about a user on Twitter
SLRequest *twitterInfoRequest = [SLRequest requestForServiceType:SLServiceTypeTwitter requestMethod:SLRequestMethodGET URL:[NSURL URLWithString:#"https://api.twitter.com/1.1/users/show.json"] parameters:[NSDictionary dictionaryWithObject:twitterAccount.username forKey:#"screen_name"]];
[twitterInfoRequest setAccount:twitterAccount];
// Making the request
[twitterInfoRequest performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) {
dispatch_async(dispatch_get_main_queue(), ^{
// Check if we reached the reate limit
if ([urlResponse statusCode] == 429) {
NSLog(#"Rate limit reached");
return;
}
// Check if there was an error
if (error) {
NSLog(#"Error: %#", error.localizedDescription);
return;
}
// Check if there is some response data
if (responseData) {
NSError *error = nil;
NSArray *TWData = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableLeaves error:&error];
// Filter the preferred data
NSString *screen_name = [(NSDictionary *)TWData objectForKey:#"screen_name"];
NSString *name = [(NSDictionary *)TWData objectForKey:#"name"];
int followers = [[(NSDictionary *)TWData objectForKey:#"followers_count"] integerValue];
int following = [[(NSDictionary *)TWData objectForKey:#"friends_count"] integerValue];
}
});
}];
}
} else {
NSLog(#"No access granted");
}
}];
}
Getting list of followers
To get list of followers, change the URL you are requesting to:
https://api.twitter.com/1.1/followers/list.json
It returns a cursored collection of user objects for users following the specified user.
Getting list of followed users
To get list of the users you follow, change the URL you are requesting to:
https://api.twitter.com/1.1/friends/list.json
It returns a cursored collection of user objects for every user the specified user is following (otherwise known as their "friends").
I used your code to test it and it works. Based on REST API v1.1 Resources
You can use Criexe API, if you don't want use API.
https://github.com/criexe/api/wiki/Social-Networks-Page-Stats-API
Example:
GET https://api.criexe.com/social/pageStats?twitter=microsoft
{
"twitter":{
"user":"microsoft",
"followers":8293150
},
"total":8293150
}

Twitter Account always returns blank timeline?

I have recently begun an Xcode project, and it requires me to get the feed, or timeline, from a Twitter account. I am following this tutorial. Although when I compile my code, it has no errors, it does not log any tweets. I also downloaded the source code for the project, but it still returns nothing. I realize that it could be a problem from my account, but I have tweeted something recently, followed some people, retweeted, basically everything you could do to update a timeline! Thanks for the help!
Twitter Account:#Pushahk
-(void)getTwitterFeed{
ACAccountStore *account = [[ACAccountStore alloc] init];
ACAccountType *accountType = [account accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];
[account requestAccessToAccountsWithType:accountType options:nil completion:^(BOOL granted, NSError *error){
if (granted == YES) {
NSArray *arrayOfAccounts = [account accountsWithAccountType:accountType];
if ([arrayOfAccounts count] > 0) {
ACAccount *twitterAccount = [arrayOfAccounts lastObject];
NSURL *requestAPI = [NSURL URLWithString:#"http://api.twitter.com/1.1/statuses/user_timeline.json"];
NSMutableDictionary *parameters = [[NSMutableDictionary alloc] init];
[parameters setObject:#"100" forKey:#"count"];
[parameters setObject:#"1" forKey:#"include_entities"];
SLRequest *posts = [SLRequest requestForServiceType:SLServiceTypeTwitter requestMethod:SLRequestMethodGET URL:requestAPI parameters:parameters];
posts.account = twitterAccount;
[posts performRequestWithHandler:
^(NSData *response, NSHTTPURLResponse
*urlResponse, NSError *error)
{
// The NSJSONSerialization class is then used to parse the data returned and assign it to our array.
self.TwitterPosts = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableLeaves error:&error];
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(#"Hi");
for (int i = 0; i < [self.TwitterPosts count]; i++) {
NSLog(#"%#", [self.TwitterPosts objectAtIndex:i]);
NSLog(#"Hi");
}
});
}];
}
}
else{
NSLog(#"%#", [error localizedDescription]);
}
}];
}
It's because include_entities is no longer a valid parameter within the v1.1 API (it was in the v1 API). You may also need to provide a screen name, as I believe setting the .account property on the request is only for OAuth purposes.
Source: http://dev.twitter.com/docs/api/1.1/get/statuses/user_timeline

Retrieving Twitter OAuth Token using Social Framework and account frame work in iPhone?

I Had an application in which i am doing twitter login to access the users basic info.i am using social&account frame work.all working fine,
`if([self userHasAccessToTwitter])
{
ACAccountStore *accountStore = [[ACAccountStore alloc] init];
ACAccountType *accountType = [accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];
[accountStore requestAccessToAccountsWithType:accountType options:nil completion:^(BOOL granted, NSError *error){
if (granted) {
NSArray *accounts = [accountStore accountsWithAccountType:accountType];
// Check if the users has setup at least one Twitter account
if (accounts.count > 0)
{
ACAccount *twitterAccount = [accounts objectAtIndex:0];
// Creating a request to get the info about a user on Twitter
SLRequest *twitterInfoRequest = [SLRequest requestForServiceType:SLServiceTypeTwitter requestMethod:SLRequestMethodGET URL:[NSURL URLWithString:#"https://api.twitter.com/1.1/users/show.json"] parameters:[NSDictionary dictionaryWithObject:twitterAccount.username forKey:#"screen_name"]];
[twitterInfoRequest setAccount:twitterAccount];
// Making the request
[twitterInfoRequest performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) {
dispatch_async(dispatch_get_main_queue(), ^{
// Check if we reached the reate limit
if ([urlResponse statusCode] == 429) {
NSLog(#"Rate limit reached");
return;
}
// Check if there was an error
if (error) {
NSLog(#"Error: %#", error.localizedDescription);
return;
}
// Check if there is some response data
if (responseData) {
NSError *error = nil;
NSArray *TWData = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableLeaves error:&error];
NSString *profileImageStringURL = [(NSDictionary *)TWData objectForKey:#"profile_image_url"];
// Update the interface with the loaded data
[self getProfileImageForURLString:profileImageStringURL];
}
});
}];
}
}
`
But if he is not configured any accounts in the settings i need to do a custom login like in instagram,using xAuth login.Can anybody help me ,I had gone through this
Retrieving Twitter OAuth Token using Social Framework (iOS6)
But nothing seems to be clear to me,how to make an SLrequest with username and password to access the auth token and make him to login to twitter is the pbm confusing me.can anybody guide me on this?

Twitter Follow API

I need to get the person is following another person in twitter using the API.
I know the twitter migrated to v1.1
I used these API to get the relationship between two person,
https://api.twitter.com/1.1/friendships/exists.json?screen_name_a=Person1&screen_name_b=Person2
https://api.twitter.com/1.1/friendships/lookup.json?screen_name=Person1,Person2
But i get the final result is,
{
errors = (
{
code = 215;
message = "Bad Authentication data";
}
);
}
Is there any other exact API to find the my solution.
Any one help me to find the one person is following the another one.
Try this code you can get what you are expecting,
-(void) followUsOnTwitter {
ACAccountStore *accountStore = [[ACAccountStore alloc] init];
ACAccountType *accountType = [accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];
[accountStore requestAccessToAccountsWithType:accountType withCompletionHandler:^(BOOL granted, NSError *error) {
if(granted) {
// Get the list of Twitter accounts.
NSArray *accountsArray = [accountStore accountsWithAccountType:accountType];
// For the sake of brevity, we'll assume there is only one Twitter account present.
// You would ideally ask the user which account they want to tweet from, if there is more than one Twitter account present.
if ([accountsArray count] > 0) {
// Grab the initial Twitter account to tweet from.
ACAccount *twitterAccount = [accountsArray objectAtIndex:0];
NSMutableDictionary *tempDict = [[NSMutableDictionary alloc] init];
[tempDict setValue:#"abcd" forKey:#"screen_name"]; // Change the Value String
[tempDict setValue:#"true" forKey:#"follow"];
TWRequest *postRequest = [[TWRequest alloc] initWithURL:[NSURL URLWithString:#"https://api.twitter.com/1.1/friendships/create.json"]
parameters:tempDict
requestMethod:TWRequestMethodPOST];
[postRequest setAccount:twitterAccount];
[postRequest performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) {
NSString *output = [NSString stringWithFormat:#"HTTP response status: %i", [urlResponse statusCode]];
NSLog(#"%#", output);
if (urlResponse.statusCode == 200)
{
// follow by usr
}
}];
}
}
}];
}
you can check with this answer :
In the v1.1 API, they have replaced it with the friendships/lookup API where you can specify a comma separated list of up to 100 users and it'll tell you about the connections between the authenticating user and each of the users specified

return nsmutablearray from twitter account block

I am trying to make a function which returns a list of twitter users but I am not able to make the function return a nsmutablearray. Here it is the code I execute
-(NSMutableArray*) getTwitterUsersInPosition: (Position*) position
{
// Request access to the Twitter accounts
ACAccountStore *accountStore = [[ACAccountStore alloc] init];
ACAccountType *accountType = [accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];
[accountStore requestAccessToAccountsWithType:accountType options:nil completion:^(BOOL granted, NSError *error){
if (granted) {
NSArray *accounts = [accountStore accountsWithAccountType:accountType];
// Check if the users has setup at least one Twitter account
if (accounts.count > 0)
{
ACAccount *twitterAccount = [accounts objectAtIndex:0];
// Creating a request to get the info about a user on Twitter
NSArray *keys = [NSArray arrayWithObjects:#"geocode", #"count", nil];
NSArray *objects = [NSArray arrayWithObjects:#"37.781157,-122.398720,100mi", #"2", nil];
NSDictionary *dictionary = [NSDictionary dictionaryWithObjects:objects
forKeys:keys];
SLRequest *twitterInfoRequest = [SLRequest requestForServiceType:SLServiceTypeTwitter requestMethod:SLRequestMethodGET URL:[NSURL URLWithString:#"https://api.twitter.com/1.1/search/tweets.json"] parameters:dictionary];
[twitterInfoRequest setAccount:twitterAccount];
// Making the request
[twitterInfoRequest performRequestWithHandler: ^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) {
dispatch_async(dispatch_get_main_queue(), ^{
// Check if we reached the rate limit
if ([urlResponse statusCode] == 429) {
NSLog(#"Rate limit reached");
return;
}
// Check if there was an error
if (error) {
NSLog(#"Error: %#", error.localizedDescription);
return;
}
// Check if there is some response data
if (responseData) {
NSError *error = nil;
NSArray *TWData = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableLeaves error:&error];
NSMutableArray *usersArray= [[NSMutableArray alloc] init];
NSMutableArray* statuses= [(NSDictionary *) TWData objectForKey:#"statuses"];
for (NSDictionary* dict in statuses )
{
NSString* user = [[dict objectForKey:#"user"] objectForKey:#"screen_name"];
NSLog(#"%#",user);
[usersArray addObject:user];
}
return userArray; //Here it says "Return type 'NSMutabelArray *' must match previous type 'void' when block literal has unspecified return type
}
});
}];
}
} else {
NSLog(#"No access granted");
}
}];
}
Thanks for your help.
Your method can NOT have a return type because the value you want to return is obtained asynchronously and isn't available until after the method has completed.
You need to rewrite your method so that it returns the data:
To a delegate
Via a block
Into an instance variable and triggers some update
Via a notification
Basically some mechanism that allows you to deal with the asynchronous response. Please don't make the call synchronous.
In the middle of your code you simply write return without a value (as if your method has return type of void):
if ([urlResponse statusCode] == 429) {
NSLog(#"Rate limit reached");
return;
}
// Check if there was an error
if (error) {
NSLog(#"Error: %#", error.localizedDescription);
return;
Change it to return nil and the code should compile.

Resources