好吧,讓說你要顯示的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用戶信息,see their docs。
感謝烏拉圭回合的答覆...但我需要的響應,用戶的個人信息的JSON ... – 2012-04-13 09:18:39
@RahulNair對不起我的水晶球沒有告訴我關於 – AnthonyBlake 2012-04-13 09:45:11