All
Я довольно новичок в XCode и пытаюсь понять, как лучше всего решать проблемы с подключением при попытке использовать WebView. Я знаю, что есть вопросы, связанные с SO, но ни один из них не предлагает полных решений. У меня есть следующий код, но он кажется немного неэффективным. Надеюсь, кто-нибудь может помочь мне провести его рефакторинг до такой степени, что его можно будет использовать везде, где называется UIWebView.
ПРИМЕЧАНИЕ. Пожалуйста, пока игнорируйте проблемы с памятью. Я понимаю, что это тоже нужно добавить.
- (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];
}
Полагаю, меня интересует, есть ли какие-нибудь ярлыки для достижения желаемой функциональности? Могу ли я как-то получить доступ к URLResponse через WebView напрямую? Имеет ли значение nil для URLConnection или UIWebView ошибки в соединении без явной проверки их? Есть ли более простой способ передать URLRequest в методы делегата, чтобы он не создавался повторно дважды?
Заранее спасибо!