假设你想在表格中显示用户设备上的Twitter账户。你可能想要在表格单元格中显示头像,这样你就需要查询Twitter的API。
假设你有一个NSArray
的ACAccount
对象,你可以创建一个字典来存储每个账户的额外资料。你的表视图控制器的tableView:cellForRowAtIndexPath:
方法需要添加以下代码:
UIImage *profileImage = nil;
NSDictionary *info = [self.twitterProfileInfos objectForKey:account.identifier];
if (info) profileImage = [info objectForKey:kTwitterProfileImageKey];
if (profileImage) {
cell.imageView.image = profileImage;
} else {
[self getTwitterProfileImageForAccount:account completion:^ {
[self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
}];
}
这段代码的作用是从一个字典中通过账户标识和静态字符串键获取UIImage
对象。如果没有获得图像对象,则调用一个实例方法,传入一个完成处理器块,重新加载表格行。实例方法看起来有点像这样:
#pragma mark - Twitter
- (void)getTwitterProfileImageForAccount:(ACAccount *)account completion:(void(^)(void))completion {
NSURL *url = [NSURL URLWithString:@"users/profile_image" relativeToURL:kTwitterApiRootURL];
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
account.username, @"screen_name",
@"bigger", @"size",
nil];
TWRequest *request = [[TWRequest alloc] initWithURL:url parameters:params requestMethod:TWRequestMethodGET];
[request performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) {
if (!responseData && error) {
abort();
}
UIImage *profileImg = [UIImage imageWithData:responseData];
NSMutableDictionary *info = [self.twitterProfileInfos objectForKey:account.identifier];
if (!info) {
info = [NSMutableDictionary dictionary];
[self.twitterProfileInfos setObject:info forKey:account.identifier];
}
[info setObject:profileImg forKey:kTwitterProfileImageKey];
if (completion) dispatch_async(dispatch_get_main_queue(), completion);
}];
}
因此,请确保您优雅地失败,但是在下载配置文件图像时会更新表格。在完成处理程序中,您可以将它们放入图像缓存中,或者以其他方式使它们超出类的生命周期。
可以使用相同的过程访问其他Twitter用户信息,请参阅他们的文档。