Соединение веб-просмотра XCode / обработка ошибок сервера - PullRequest
0 голосов
/ 23 сентября 2010

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 в методы делегата, чтобы он не создавался повторно дважды?

Заранее спасибо!

1 Ответ

5 голосов
/ 23 сентября 2010
- (void)viewDidLoad {
    webView = [[UIWebView alloc]init];
    [webView setDelegate:self];
    [webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://yourUrl.com"]]]
    [super viewDidLoad];
}

#pragma mark UIWebView delegate methods
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
    //read your request here
    //before the webview will load your request
    return YES;
}
- (void)webViewDidStartLoad:(UIWebView *)webView{
    //access your request
    webView.request;
}
- (void)webViewDidFinishLoad:(UIWebView *)webView{
    //access your request 
    webView.request;    
}
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{
    NSLog(@"could not load the website caused by error: %@", error);
}
-(void)dealloc{
[webView release];
[super dealloc];
}

Вы можете загрузить веб-страницу с помощью NSURLRequest прямо в свое веб-представление.С помощью методов обратного вызова делегата вы можете изменить поведение вашего веб-просмотра.

С этим фрагментом кода вы должны сделать это.

...