0

I am developing a login application. I have a registration view, I'm using sendAsynchronousRequest to send registration request.When I received a data back I want to show alert view displaying the registration if valid. Now my problem is When I received a data back the UI get blocked until alert view display.

why is that happen and how could I fix it ? check the the code snippet:

[NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {

        error = connectionError;

        NSMutableDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil ];

        if ([dic count] == 1) {
            [dic valueForKey:@"RegisterUserResult"];

            UIAlertView *alertview = [[UIAlertView alloc] initWithTitle:@"Registration" message:[dic valueForKey:@"RegisterUserResult"] delegate:self cancelButtonTitle:@"cancel" otherButtonTitles:nil];

            [alertview show];
        }else {
            UIAlertView *alertview = [[UIAlertView alloc] initWithTitle:@"Registration" message:[dic valueForKey:@"ErrorMessage"] delegate:self cancelButtonTitle:@"cancel" otherButtonTitles:nil];
            [alertview show];
        }

        [self printData:data];

1 Answer 1

2

You try to perform UI operations on non-main thread because completion block executes on you custom operation queue.

You need to wrap all UI calls in

dispatch_async(dispatch_get_main_queue(), ^{
......
});

within custom operation queue non-main threads.

So, in your code any call for UIAlertView will looks like

dispatch_async(dispatch_get_main_queue(), ^{

        UIAlertView *alertview = [[UIAlertView alloc] initWithTitle:@"Registration" message:[dic valueForKey:@"RegisterUserResult"] delegate:self cancelButtonTitle:@"cancel" otherButtonTitles:nil];

        [alertview show];
});

If you have no heavy operations in your completion handler you can dispatch it on main thread directly setting queue to [NSOperationQueue mainQueue]

[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {...}];
2
  • could you explain more please?
    – mustafa
    May 3, 2015 at 12:17
  • 1
    @mustafa, I've added details to the answer
    – malex
    May 3, 2015 at 12:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.