为用户 ID 获取 Twitter 用户名实际上比应有的要费力得多。Facebook SDK 使类似的过程变得更加容易(从没想过我会这么说......)。
无论如何,要发出 Twitter 信息请求,您需要将您选择的帐户从帐户商店附加到 TWRequest:
NSURL *url = [NSURL URLWithString:@"https://api.twitter.com/1.1/users/show.json"];
NSMutableDictionary *params = [NSMutableDictionary new];
[params setObject:tempUserID forKey:@"user_id"];
[params setObject:@"0" forKey:@"include_rts"]; // don't include retweets
[params setObject:@"1" forKey:@"trim_user"]; // trim the user information
[params setObject:@"1" forKey:@"count"]; // i don't even know what this does but it does something useful
TWRequest *request = [[TWRequest alloc] initWithURL:url parameters:params requestMethod:TWRequestMethodGET];
// Attach an account to the request
[request setAccount:twitterAccount]; // this can be any Twitter account obtained from the Account store
[request performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) {
if (responseData) {
NSDictionary *twitterData = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingAllowFragments error:NULL];
NSLog(@"received Twitter data: %@", twitterData);
// to do something useful with this data:
NSString *screen_name = [twitterData objectForKey:@"screen_name"]; // the screen name you were after
dispatch_async(dispatch_get_main_queue(), ^{
// update your UI in here
twitterScreenNameLabel.text = screen_name;
});
// A handy bonus tip: twitter display picture
NSString *profileImageUrl = [twitterData objectForKey:@"profile_image_url"];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:profileImageUrl]];
UIImage *image = [UIImage imageWithData:imageData]; // the matching profile image
dispatch_async(dispatch_get_main_queue(), ^{
// assign it to an imageview in your UI here
twitterProfileImageView.image = image;
});
});
}else{
NSLog(@"Error while downloading Twitter user data: %@", error);
}
}];
请注意我如何将接口更新内容包装在异步块中。这是为了确保界面不会冻结。我还为检索用户的个人资料图像提供了奖励提示,您是否如此倾向于。