I have a tabbed bar application in which one of the buttons loads the content of a webpage to a UIWebView. The problem I am facing is that while the connection attempting to fetch the data the tab bar buttons are non responsive until either the page is done loading or connection has failed. Is there a better way to perform this operation so the user can switch out of that tab if he/she changes their mind for example. Thanks and here is the code:

- (void)loadThrillsSite
{
    [self.webView setDelegate:self];
    NSString *urlString = @"https://www.Thrills.in";
    NSURL *url = [NSURL URLWithString:urlString];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];

    NSOperationQueue *queue = [[NSOperationQueue alloc] init];

    [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
     {
         if ([data length] > 0 && error == nil) [self.webView loadRequest:request];
         else if (error != nil) {
             UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Connection Error!" message:@"Failed to connect to server\nPlease check your internet connection and try again" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
             [alert show];
         }
     }];
}

- (void)webViewDidFinishLoad:(UIWebView *)webView;
{
    [hudImageView removeFromSuperview];

    [self.spinner stopAnimating];

    [patternView removeFromSuperview];
}
有帮助吗?

解决方案

UIWebView's loadRequest method description:

Connects to a given URL by initiating an asynchronous client request.

It already makes a asynchronous call so you do not need to use another block. Just call [self.webView loadRequest:request]; You can handle errors on - (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error method.

Other notes: Your url is not working right now and do not do any UI related work like showing an alert view on background thread. Hope it helps.

- (void)loadThrillsSite
{
    [self.webView setDelegate:self];
    NSString *urlString = @"https://www.Thrills.in";
    NSURL *url = [NSURL URLWithString:urlString];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];

    [self.webView loadRequest:request];
}

- (void)webViewDidFinishLoad:(UIWebView *)webView;
{
    [hudImageView removeFromSuperview];

    [self.spinner stopAnimating];

    [patternView removeFromSuperview];
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Connection Error!" message:@"Failed to connect to server\nPlease check your internet connection and try again" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
    [alert show];
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top