使用webview如何做超时判断

在加载网页时给一个timer定时器,规定超时时间,然后再超时时间的方法中提示超时

 

如果没有超时,则在webview协议中的“加载完成”方法中 取消timer定时器

 

- (void)openWebView
{
    if (timer) {
        [timer invalidate];
    }
    timer = [NSTimer scheduledTimerWithTimeInterval:10.0 target:self selector:@selector(timerFunction) userInfo:nil repeats:NO];
    
    if (!webViewFirst) {
        webViewFirst = [[UIWebView alloc] init];
        webViewFirst.frame = CGRectMake(0, 0, ivWelcome.frame.size.width, ivWelcome.frame.size.height);
        webViewFirst.backgroundColor = [UIColor whiteColor];
        webViewFirst.delegate = self;
        webViewFirst.hidden = YES;
        [webViewFirst loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:[kGlobal getLoadingUrl]]]];
        [ivWelcome addSubview:webViewFirst];
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.frame = CGRectMake(0, 0, ivWelcome.frame.size.width, ivWelcome.frame.size.height);
        btn.backgroundColor = [UIColor clearColor];
        btn.enabled = NO;
        [btn addTarget:self action:@selector(initLoginView) forControlEvents:UIControlEventTouchUpInside];
        [ivWelcome addSubview:btn];
        btnSkip = btn;
    }
    else {
        webViewFirst.hidden = YES;
        [webViewFirst reload];
    }
}
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    if (timer) {
        [timer invalidate];
    }
    btnSkip.enabled = YES;
    webViewFirst.hidden = NO;
    {//添加淡入淡出动画
        CATransition *animation = [CATransition animation];
        //animation.delegate = self;
        // 设定动画时间
        animation.duration = 0.7;
        // 设定动画快慢(开始与结束时较慢)
        animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
        animation.type = kCATransitionFade;
        [webViewFirst.layer addAnimation:animation forKey:@"animation"];
    }
}
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
    [self timerFunction];
}
- (void)timerFunction
{
    if (timer) {
        [timer invalidate];
    }
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"网络不给力,请重试" delegate:kAPPDELEGATE cancelButtonTitle:@"重试" otherButtonTitles:nil];
    [alert show];
}

 

posted @ 2015-01-15 10:01  爱生活爱代码  阅读(1439)  评论(0编辑  收藏  举报