I am doing a Twitter App using the Twitter iOS 5 Framwork and it works quite well.
I am searching for all available TwitterAccounts on the device and load them into a tableview to display them. If the user touches on a account the next view is loaded and all followers are requested via the REST API and loaded into a array to parse each name and photo using the REST API. The problem is, the request isn’t asynchronous and I am first getting a nil array and then getting the response of the API.
The requestMethod is the following:
__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;
}
and the loading process:
- (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];
}
and the Output:
followerIDArray: (
)
2011-12-03 21:43:33.305 NBNTwitterChat[1858:10403] responseArray (
3840,
14064174,
281136865,
224987906
) for user:xyz
Can anyone assist me with that? I searched the whole web and I need to use the TWRequest method and not the asihttprequest or something else.
Actually I’d say that it is asynchronous, which is causing the problem.
-[TWRequest performRequestWithHandler:]is an asynchronous method that will return instantly. You cannot returnresponseArraylike you do, since it won’t be filled before leaving the function.You will have to write asynchronous code, or you will have to use
-[TWRequest signedURLRequest]and do a synchronous request.