iPhone的Twitter API获取用户的关注者/关注
我希望能够使用Twitter的ios 5的API来获取所有的用户追随者和用户名到一个NSDictionary
…
我已经打了一个路障。 我不知道如何使用Twitter的API这样做…但我的主要问题是获取用户的用户名。 如果我甚至不知道用户的用户名,我怎么能find这个用户关注者的API请求呢?
有人能给我一个例子让你的Twitter用户追随者和跟随?
PS:我已经添加了Twitter框架,并导入
这是苹果的Twitter API和Twitter自己的API的结合。 一旦阅读代码,这是相当直接的。 我将提供如何获取Twitter帐户的“朋友”的示例代码(这是用户所关注的用户的用语),这应该足以让您继续获得关注用户的方法帐户。
首先,添加Accounts
和Twitter
框架。
现在,让我们来看看用户设备上的Twitter帐户。
#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.) } }]; }
现在我们可以使用GET friends / ids命令获取帐户的朋友 :
#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); }]; }
当你想要追随者的帐户,它几乎是一样的…简单地使用URL http://api.twitter.com/1/followers/ids.format
并通过GET追随者/ ID传递所需的参数
希望这给你一个良好的开端。
更新:
正如在评论中指出的,你应该使用更新的API调用: https://api.twitter.com/1.1/followers/list.json
: https://api.twitter.com/1.1/followers/list.json
-
参考runmad的post,“ [__NSArrayI objectAtIndex::index 0超出空数组界限 ”的错误来源的意见是你没有在模拟器中设置twitter帐户。 您需要使用您的用户名和Twitter提供的临时密码来签署Twitter。
-
其他的错误来源是“setObject for key error,key id is nil”。 为了克服以下代码的types: –
-(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); }]; }
使用FHSTwitterEngine
#import“FHSTwitterEngine.h”
添加SystemConfiguration.framework
把下面的代码写到你的viewDidLoad(用于oauthlogin)
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"]); } }