我有一个标签栏应用程序,其中一个按钮将网页内容加载到UIWebView。 我面临的问题是,当尝试获取数据的连接时,标签栏按钮无响应,直到页面完成加载或连接失败。 是否有更好的方法来执行此操作,以便用户可以在他/她改变主意时切换出该选项卡。 谢谢,这是代码:
- (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];
}
答案 0 :(得分:1)
UIWebView
的loadRequest方法说明:
通过启动异步客户端请求连接到给定的URL。
它已经进行了异步调用,因此您不需要使用其他块。只需致电[self.webView loadRequest:request];
即可处理- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
方法的错误。
其他说明:您的网址目前无法正常工作,也不会执行任何与UI相关的工作,例如在后台线程上显示警报视图。希望它有所帮助。
- (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];
}