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];
mustafa
  • 451
  • 6
  • 15

1 Answers1

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) {...}];
malex
  • 9,874
  • 3
  • 56
  • 77