好吧,假设您想在表格中显示用户在其设备上拥有的 Twitter 帐户。您可能希望在表格单元格中显示头像,在这种情况下您需要查询 Twitter 的 API。
假设您有一个NSArray
对象ACAccount
,您可以创建一个字典来存储每个帐户的额外配置文件信息。你的表视图控制器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
从字典字典中访问一个对象,由帐户标识符和静态键作为NSString
键。如果它没有得到一个图像对象,那么它调用一个实例方法,传入一个完成处理程序块,它重新加载表行。实例方法看起来有点像这样:
#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 用户信息,请参阅他们的文档。