Manipulação de erros de conexão / servidor XCode na webview
Tudo,
Eu sou bastante novo no XCode e estou tentando entender como lidar melhor com problemas de conexão ao tentar usar um WebView. Sei que há perguntas relacionadas ao SO, mas nenhuma parece oferecer soluções completas. Eu tenho o código a seguir, mas parece um pouco ineficiente. Felizmente, alguém pode me ajudar a refatorá-lo a um ponto em que possa ser usado em qualquer lugar em que um UIWebView seja chamado.
NOTA: Ignore os problemas de memória por enquanto. Sei que isso também deve ser adicionado.
- (void)viewDidLoad {
[webView setDelegate:self];
NSString *urlAddress = @"http://www.somesite.com/somepage";
NSURL *url = [NSURL URLWithString:urlAddress];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
NSURLConnection *urlConnection = [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self];
[super viewDidLoad];
}
// Check for URLConnection failure
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
UIAlertView *connectionError = [[UIAlertView alloc] initWithTitle:@"Connection error" message:@"Error connecting to page. Please check your 3G and/or Wifi settings." delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
[connectionError show];
webView.hidden = true;
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
//Check for server error
if ([httpResponse statusCode] >= 400) {
UIAlertView *serverError = [[UIAlertView alloc] initWithTitle:@"Server error" message:@"Error connecting to page. If error persists, please contact support." delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
[serverError show];
webView.hidden = true;
//Otherwise load webView
} else {
// Redundant code
NSString *urlAddress = @"http://somesite.com/somepage";
NSURL *url = [NSURL URLWithString:urlAddress];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
[webView loadRequest:urlRequest];
webView.hidden = false;
}
}
// Seems redundant since we are already checking the URLConnection
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
UIAlertView *connectionError = [[UIAlertView alloc] initWithTitle:@"Connection error" message:@"Error connecting to page. Please check your 3G and/or Wifi settings." delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
[connectionError show];
}
Acho que o que estou pensando é: existem atalhos para alcançar a funcionalidade desejada? De alguma forma, posso acessar o URLResponse diretamente pelo WebView? Um valor nulo para o URLConnection ou o UIWebView implica erros de conexão sem precisar verificar explicitamente por eles? Existe uma maneira mais fácil de passar o URLRequest para os métodos delegados, para que ele não tenha sido recriado duas vezes?
Desde já, obrigado!