在載入網頁時給一個timer定時器,規定超時時間,然後再超時時間的方法中提示超時

如果沒有超時,則在webview協議中的“載入完成”方法中 取消timer定時器

  1. - (void)openWebView
  2. {
  3. if (timer) {
  4. [timer invalidate];
  5. }
  6. timer = [NSTimer scheduledTimerWithTimeInterval:10.0 target:self selector:@selector(timerFunction) userInfo:nil repeats:NO];
  7.  
  8. if (!webViewFirst) {
  9. webViewFirst = [[UIWebView alloc] init];
  10. webViewFirst.frame = CGRectMake(, , ivWelcome.frame.size.width, ivWelcome.frame.size.height);
  11. webViewFirst.backgroundColor = [UIColor whiteColor];
  12. webViewFirst.delegate = self;
  13. webViewFirst.hidden = YES;
  14. [webViewFirst loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:[kGlobal getLoadingUrl]]]];
  15. [ivWelcome addSubview:webViewFirst];
  16. UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
  17. btn.frame = CGRectMake(, , ivWelcome.frame.size.width, ivWelcome.frame.size.height);
  18. btn.backgroundColor = [UIColor clearColor];
  19. btn.enabled = NO;
  20. [btn addTarget:self action:@selector(initLoginView) forControlEvents:UIControlEventTouchUpInside];
  21. [ivWelcome addSubview:btn];
  22. btnSkip = btn;
  23. }
  24. else {
  25. webViewFirst.hidden = YES;
  26. [webViewFirst reload];
  27. }
  28. }
  29. - (void)webViewDidFinishLoad:(UIWebView *)webView
  30. {
  31. if (timer) {
  32. [timer invalidate];
  33. }
  34. btnSkip.enabled = YES;
  35. webViewFirst.hidden = NO;
  36. {//新增淡入淡出動畫
  37. CATransition *animation = [CATransition animation];
  38. //animation.delegate = self;
  39. // 設定動畫時間
  40. animation.duration = 0.7;
  41. // 設定動畫快慢(開始與結束時較慢)
  42. animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
  43. animation.type = kCATransitionFade;
  44. [webViewFirst.layer addAnimation:animation forKey:@"animation"];
  45. }
  46. }
  47. - (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
  48. {
  49. [self timerFunction];
  50. }
  51. - (void)timerFunction
  52. {
  53. if (timer) {
  54. [timer invalidate];
  55. }
  56. UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"網路不給力,請重試" delegate:kAPPDELEGATE cancelButtonTitle:@"重試" otherButtonTitles:nil];
  57. [alert show];
  58. }