Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iPhone- Twitter API GET Users Followers/Following

I want to be able to use the Twitter API for ios 5 to get all of the user followers and following user name into a NSDictionary...

I've hit a road block though. I don't know how to use the Twitter API the do this... But my main problem is getting the user's username in the first place. How can I make an API request to find this users followers when I don't even know the users username?

Can someone give me an example on getting your Twitter users followers and following?

PS: I've already added the Twitter framework, and imported

like image 831
The Man Avatar asked Jul 22 '12 13:07

The Man


3 Answers

It's a combination of Apple's Twitter API and Twitter's own API. It's fairly straight forward once you read the code. I'm going to provide sample code for how to get the 'friends' for a Twitter account (this is the term for people that a user follows), which should be enough to get you going on a method to obtain the followers for an account.

First, add the Accounts and Twitter frameworks.

Now, let's get the Twitter account(s) present on a user's device.

#import <Accounts/Accounts.h>

-(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.)
                                }
    }];
}

Now we can get the friends for an account using the GET friends/ids command:

#import <Twitter/Twitter.h>

-(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:NSJSONWritingPrettyPrinted 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);
    }];
}

When you want the followers for an account, it's almost the same... Simple use the URL http://api.twitter.com/1/followers/ids.format and pass in the needed parameters as found via GET followers/ids

Hope this gives you a good head start.

UPDATE:

As pointed out in the comments, you should be using the updated API call: https://api.twitter.com/1.1/followers/list.json

like image 125
runmad Avatar answered Nov 15 '22 19:11

runmad


  1. Referring to comments on post of runmad the source of error for "[__NSArrayI objectAtIndex:]: index 0 beyond bounds for empty array" is that you have not setup twitter account in simulator. You need to sign twitter with your username and a temporary password provided by twitter.

  2. Other source of error is "setObject for key error, key id is nil". To overcome that type below code : -

-(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:@"https://api.twitter.com/1.1/followers/list.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:NSJSONWritingPrettyPrinted error:&jsonError];
        
        NSLog(@"%@", twitterFriends);
    }];
}

import

import

Note:- TWRequest has being deprecated. So instead you can also use this snippet:

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:twitterAccount.username])
 {
 twitterAccount = t;
 break;
 }
 }

 SLRequest *twitterInfoRequest = [SLRequest requestForServiceType:SLServiceTypeTwitter requestMethod:SLRequestMethodGET URL:[NSURL URLWithString:@"https://api.twitter.com/1.1/followers/list.json"] parameters:[NSDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@"%@", twitterAccount.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];
 NSLog(@"TWData : %@", TWData);

 }
 });
 }];
 }
 } else {
 NSLog(@"No access granted");
 }
 }];
like image 40
Hemanshu Liya Avatar answered Nov 15 '22 19:11

Hemanshu Liya


Use FHSTwitterEngine

#import "FHSTwitterEngine.h"

Add SystemConfiguration.framework

Write following code to your viewDidLoad(for oauth login)

UIButton *logIn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
logIn.frame = CGRectMake(100, 100, 100, 100);
[logIn setTitle:@"Login" forState:UIControlStateNormal];
[logIn addTarget:self action:@selector(showLoginWindow:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:logIn];

[[FHSTwitterEngine sharedEngine]permanentlySetConsumerKey:@"Xg3ACDprWAH8loEPjMzRg" andSecret:@"9LwYDxw1iTc6D9ebHdrYCZrJP4lJhQv5uf4ueiPHvJ0"];
[[FHSTwitterEngine sharedEngine]setDelegate:self];


 - (void)showLoginWindow:(id)sender {
UIViewController *loginController = [[FHSTwitterEngine sharedEngine]loginControllerWithCompletionHandler:^(BOOL success) {
    NSLog(success?@"L0L success":@"O noes!!! Loggen faylur!!!");
    [[FHSTwitterEngine sharedEngine]loadAccessToken];
    NSString *username = [FHSTwitterEngine sharedEngine].authenticatedUsername;
    NSLog(@"user name is :%@",username);
    if (username.length > 0) {
        [self listResults];
    }
}];
     [self presentViewController:loginController animated:YES completion:nil];
}
 - (void)listResults {

NSString *username = [FHSTwitterEngine sharedEngine].authenticatedUsername;
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"]);
}
}
like image 32
Mohit Avatar answered Nov 15 '22 20:11

Mohit