0

我正在开发一个登录应用程序。我有一个注册视图,我正在使用 sendAsynchronousRequest 发送注册请求。当我收到返回的数据时,我想显示警报视图以显示注册(如果有效)。现在我的问题是当我收到返回的数据时,UI 会被阻止,直到显示警报视图。

为什么会发生这种情况,我该如何解决?检查代码片段:

[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];
4

1 回答 1

2

您尝试在非主线程上执行 UI 操作,因为完成块在您的自定义操作队列上执行。

您需要将所有 UI 调用包装在

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

在自定义操作队列非主线程中。

因此,在您的代码中,任何调用UIAlertView都会看起来像

dispatch_async(dispatch_get_main_queue(), ^{

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

        [alertview show];
});

如果您的完成处理程序中没有繁重的操作,您可以在主线程上调度它,直接将队列设置为[NSOperationQueue mainQueue]

[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {...}];
于 2015-05-03T11:57:16.653 回答