我正在使用Twitter iOS 5 Framwork进行推特应用,效果非常好。 我正在设备上搜索所有可用的TwitterAccounts并将它们加载到tableview中以显示它们。如果用户触摸某个帐户,则会加载下一个视图,并通过REST API请求所有关注者并将其加载到一个数组中,以使用REST API解析每个名称和照片。问题是,请求不是异步的,我首先得到一个nil数组,然后得到API的响应。
requestMethod如下:
__block NSArray *responseArray;
NSURL *tweetURL = [NSURL URLWithString:@"https://api.twitter.com/1/followers/ids.json"];
NSString *username = [[[self getAvailableTwitterAccounts] objectAtIndex:user] username];
NSMutableDictionary *parameters = [[NSMutableDictionary alloc]
initWithObjects:[NSArray arrayWithObjects:@"-1", username, @"1", nil]
forKeys:[NSArray arrayWithObjects:@"cursor", @"username", @"stringify_ids" ,nil]];
//Build request
TWRequest *getFollowerRequest = [[TWRequest alloc] initWithURL:tweetURL
parameters:parameters
requestMethod:TWRequestMethodGET];
[getFollowerRequest setAccount:[[self getAvailableTwitterAccounts] objectAtIndex:user]];
[getFollowerRequest performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error){
dispatch_async(dispatch_get_main_queue(), ^{
NSError *jsonParsingError = nil;
NSDictionary *response = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:&jsonParsingError];
responseArray = [response objectForKey:@"ids"];
NSLog(@"responseArray %@ for user: %@",responseArray,username);
});
}];
return responseArray;
}
和加载过程:
- (void)viewWillAppear:(BOOL)animated
{
followerIDArray = [[NSArray alloc] initWithArray:[[NBNTwitterConnect sharedTwitterConnect] getFollowerIDsForUser:userID]];
[super viewWillAppear:animated];
}
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
[self initDisplayArray];
}
-(void)initDisplayArray{
NSLog(@"followerIDArray: %@",followerIDArray);
[self performSelectorOnMainThread:@selector(arrayDidFinishedLoading:) withObject:nil waitUntilDone:NO];
}
-(void)arrayDidFinishedLoading:(NSArray *)array{
[self.tableView reloadData];
}
和输出:
followerIDArray: (
)
2011-12-03 21:43:33.305 NBNTwitterChat[1858:10403] responseArray (
3840,
14064174,
281136865,
224987906
) for user:xyz
任何人都可以帮助我吗?我搜索了整个网络,我需要使用TWRequest方法而不是asihttprequest或其他东西。
答案 0 :(得分:2)
实际上我会说 异步,导致问题。
-[TWRequest performRequestWithHandler:]
是一种即时返回的异步方法。你不能像你一样返回responseArray
,因为它在离开函数之前不会被填充。
您必须编写异步代码,否则您将必须使用-[TWRequest signedURLRequest]
并执行同步请求。