简体   繁体   中英

How can I get the users Twitter profile information with the Twitter framework in iOS 5?

I can post to Twitter with the following code:

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

How can I get the users Twitter profile information with the Twitter framework in iOS 5?

Well, lets says you want to display the twitter accounts the user has on their device in a table. You'll likely want to display the avatar in the table cell, in which case you'll need to query Twitter's API.

Assuming you've got an NSArray of ACAccount objects, you could create a dictionary to store extra profile information for each account. Your table view controller's tableView:cellForRowAtIndexPath: would need some code like this:

    // 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];
        }];            
    }

All this is doing is accessing a UIImage object from a dictionary of dictionaries, keyed by the account identifier and then a static NSString key. If it doesn't get an image object, then it calls an instance method, passing in a completion handler block, which reloads the table row. The instance methods looks a bit like this:

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

So, make sure you fail gracefully, but, that will then update the table as it downloads the profile images. In your completion handler you could put these in an image cache, or otherwise persist them beyond the class's lifetime.

The same procedure could be used to access other Twitter user information, see their docs .

Be aware there may be multiple accounts setup on the device;

// 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

The methods above are overcomplicating things. Simply use:

ACAccount *twitterAccount = [accountsArray objectAtIndex:0];
NSLog(twitterAccount.accountDescription);

The only possible Class for getting detailed information (within the Twitter framework) is TWRequest . I don't know it, but it seems to be a wrapper for any API Request to the twitter service.

http://developer.apple.com/library/ios/#documentation/Twitter/Reference/TWRequestClassRef/Reference/Reference.html#//apple_ref/doc/uid/TP40010942

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM