【问题标题】:iPhone- Twitter API GET Users Followers/FollowingiPhone- Twitter API 获取用户关注者/关注者
【发布时间】:2012-07-20 23:39:35
【问题描述】:

我希望能够使用 iOS 5 的 Twitter API 来获取所有用户关注者和关注用户名到 NSDictionary...

不过,我遇到了障碍。我不知道如何使用 Twitter API 来做到这一点......但我的主要问题是首先获取用户的用户名。当我什至不知道用户的用户名时,如何发出 API 请求来查找该用户的关注者?

谁能给我一个关于让你的 Twitter 用户关注和关注的例子吗?

PS:我已经添加了推特框架,并且导入了

【问题讨论】:

    标签: iphone objective-c ios ios5 twitter


    【解决方案1】:

    它是 Apple 的 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 followers/ids 找到的所需参数

    希望这能给您一个良好的开端。

    更新:

    正如 cmets 中指出的,您应该使用更新后的 API 调用:https://api.twitter.com/1.1/followers/list.json

    【讨论】:

    【解决方案2】:
    1. 在 runmad 的帖子中引用 cmets 的错误源为“[__NSArrayI objectAtIndex:]: index 0 beyond bounds for empty array” 是你没有在模拟器中设置推特账号。您需要使用您的用户名和 twitter 提供的临时密码在 twitter 上签名。

    2. 其他错误来源是“setObject for key error, key id is nil”。为了克服下面的代码类型: -

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

    进口

    进口

    注意:- TWRequest 已被弃用。所以你也可以使用这个 sn-p:

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

    【讨论】:

    【解决方案3】:

    使用FHSTwitterEngine

    #import "FHSTwitterEngine.h"

    添加SystemConfiguration.framework

    将以下代码写入您的 viewDidLoad(用于 oauth 登录)

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

    【讨论】:

    • 使用这个 URL (URL api.twitter.com/1.1/friends/ids.json?),我们得到朋友 id 但我现在想知道来自 twitter 中 userID 的用户名和用户个人资料图片。如果你知道怎么做,请告诉我?
    猜你喜欢
    • 2013-07-01
    • 2010-12-23
    • 2021-04-14
    • 2021-05-22
    • 2014-01-06
    • 2011-10-13
    • 2019-07-11
    • 1970-01-01
    • 2019-03-07
    相关资源
    最近更新 更多