如何在iOS 5中使用Twitter框架获取用户的Twitter个人资料信息?

3
我可以使用以下代码发布推文:

TWTweetComposeViewController *tweeter = [[TWTweetComposeViewController alloc] init];
        [tweeter setInitialText:@"message"];
        [tweeter addImage:image];
        [self presentModalViewController:tweeter animated:YES];

如何使用iOS 5中的Twitter框架获取用户的Twitter个人资料信息?

4个回答

6

假设你想在表格中显示用户设备上的Twitter账户。你可能想要在表格单元格中显示头像,这样你就需要查询Twitter的API。

假设你有一个NSArrayACAccount对象,你可以创建一个字典来存储每个账户的额外资料。你的表视图控制器的tableView:cellForRowAtIndexPath:方法需要添加以下代码:

    // Assuming that you've dequeued/created a UITableViewCell...

    // Check to see if we have the profile image of this account
    UIImage *profileImage = nil;
    NSDictionary *info = [self.twitterProfileInfos objectForKey:account.identifier];
    if (info) profileImage = [info objectForKey:kTwitterProfileImageKey];

    if (profileImage) {
        // You'll probably want some neat code to round the corners of the UIImageView
        // for the top/bottom cells of a grouped style `UITableView`.
        cell.imageView.image = profileImage;

    } else {
        [self getTwitterProfileImageForAccount:account completion:^ {
            // Reload this row
            [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
        }];            
    }

这段代码的作用是从一个字典中通过账户标识和静态字符串键获取UIImage对象。如果没有获得图像对象,则调用一个实例方法,传入一个完成处理器块,重新加载表格行。实例方法看起来有点像这样:

#pragma mark - Twitter

- (void)getTwitterProfileImageForAccount:(ACAccount *)account completion:(void(^)(void))completion {

    // Create the URL
    NSURL *url = [NSURL URLWithString:@"users/profile_image" relativeToURL:kTwitterApiRootURL];

    // Create the parameters
    NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
                            account.username, @"screen_name", 
                            @"bigger", @"size",
                            nil];

    // Create a TWRequest to get the the user's profile image
    TWRequest *request = [[TWRequest alloc] initWithURL:url parameters:params requestMethod:TWRequestMethodGET];

    // Execute the request
    [request performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) {

        // Handle any errors properly, not like this!        
        if (!responseData && error) {
            abort();
        }

        // We should now have some image data
        UIImage *profileImg = [UIImage imageWithData:responseData];

        // Get or create an info dictionary for this account if one doesn't already exist
        NSMutableDictionary *info = [self.twitterProfileInfos objectForKey:account.identifier];
        if (!info) {
            info = [NSMutableDictionary dictionary];            
            [self.twitterProfileInfos setObject:info forKey:account.identifier];
        }

        // Set the image in the profile
        [info setObject:profileImg forKey:kTwitterProfileImageKey];

        // Execute our own completion handler
        if (completion) dispatch_async(dispatch_get_main_queue(), completion);
    }];
}

因此,请确保您优雅地失败,但是在下载配置文件图像时会更新表格。在完成处理程序中,您可以将它们放入图像缓存中,或者以其他方式使它们超出类的生命周期。

可以使用相同的过程访问其他Twitter用户信息,请参阅他们的文档


3

请注意设备上可能设置了多个帐户;

// Is Twitter is accessible is there at least one account
  // setup on the device
  if ([TWTweetComposeViewController canSendTweet]) 
  {
    // Create account store, followed by a twitter account identifer
    account = [[ACAccountStore alloc] init];
    ACAccountType *accountType = [account accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];

    // Request access from the user to use their Twitter accounts.
    [account requestAccessToAccountsWithType:accountType withCompletionHandler:^(BOOL granted, NSError *error) 
    {
      // Did user allow us access?
      if (granted == YES)
      {
        // Populate array with all available Twitter accounts
        arrayOfAccounts = [account accountsWithAccountType:accountType];
        [arrayOfAccounts retain];

        // Populate the tableview
        if ([arrayOfAccounts count] > 0) 
          [self performSelectorOnMainThread:@selector(updateTableview) withObject:NULL waitUntilDone:NO];
      }
    }];
  }

References;

http://iosdevelopertips.com/core-services/ios-5-twitter-framework-%E2%80%93-part-3.html


谢谢您的回复...但我需要用户个人信息的JSON响应。 - Rahul Nair
1
@RahulNair 抱歉,我的水晶球没有告诉我那件事。 - AnthonyBlake

2
上述方法过于复杂。只需使用以下方法即可:
ACAccount *twitterAccount = [accountsArray objectAtIndex:0];
NSLog(twitterAccount.accountDescription);

“accountDescription” 只在 iOS8 上显示 Twitter 的用户名。 - Víctor B.

1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接