Reputation: 1
I develop a small application that connects to Twitter and gets information. I want to display this information to the user in the front end. The problem is that as the Twitter API uses threads, when I try to interact with the GUI I get the following error:
Tried to obtain the web lock from a thread other than the main thread or the web thread. This may be a result of calling to UIKit from a secondary thread.
My question is how can I know in the main thread when the response for Twitter is received so that I'm able to show it to the user?
The code goes something like this and it is in a function:
NSString * url = [[NSString alloc] initWithFormat:@"http://search.twitter.com/search.json?q=%@", query];
TWRequest * request = [[TWRequest alloc] initWithURL:[NSURL URLWithString:url] parameters:nil
requestMethod:TWRequestMethodGET];
[request performRequestWithHandler:^(NSData * responseData, NSHTTPURLResponse * urlResponse, NSError * error)
{
if ([urlResponse statusCode] == 200)
{
// format response and show to user
// show to user
}
else
{
NSLog(@"Twitter error, HTTP response: %i", [urlResponse statusCode]);
}
}];
If I try to modify the GUI from this function, I got an error.
Thanks
Upvotes: 0
Views: 1064
Reputation: 41
Making UI changes from a background thread is never allowed. In this case, you should call out with [self performSelectorOnMainThread:withObject:waitUntilDone:] in the TWRequest response block. See below
Example...
- (void)makeRequest {
NSString * url = [[NSString alloc] initWithFormat:@"http://search.twitter.com/search.json?q=%@", query];
TWRequest * request = [[TWRequest alloc] initWithURL:[NSURL URLWithString:url] parameters:nil
requestMethod:TWRequestMethodGET];
// make the request..
[request performRequestWithHandler:^(NSData * responseData, NSHTTPURLResponse * urlResponse, NSError * error)
{
if ([urlResponse statusCode] == 200)
{
[self performSelectorOnMainThread:@selector(updateUI) withObject:nil waitUntilDone:NO]
}
else
{
NSLog(@"Twitter error, HTTP response: %i", [urlResponse statusCode]);
}
}];
}
- (void)updateUI {
// here you can now update your UI safely
}
Upvotes: 4