Check if UIWebView is loaded

前端 未结 4 371
陌清茗
陌清茗 2021-02-01 21:19

I have an UIWebView in one tab that loads in viewDidLoad, but if user taps other tab the loading will be disrupted and - (void)webView:(UIWebView *)webView didFailLoad

4条回答
  •  一整个雨季
    2021-02-01 21:42

    If you haven't got it to work yet, here is a working example. It also shows an alert when failing to load, and the alert is only shown once.

    Header:

    @interface MyViewController : UIViewController  {
        BOOL wasLoaded;
        BOOL alertWasShown;
    }
    
    @property (nonatomic, retain) IBOutlet UIWebView *myWebView;
    
    @end
    

    Implementation:

    - (void)loadWebView:(NSString *)urlString {
        if (wasLoaded == NO) {
            NSURL *url = [NSURL URLWithString:urlString];
            NSURLRequest *requestObject = [NSURLRequest requestWithURL:url];
            [myWebView loadRequest:requestObject];
        }
    }
    
    - (void)viewWillAppear:(BOOL)animated {
        NSString *urlString = @"put your url here";
        [self loadWebView:urlString];
    }
    
    - (void)viewDidLoad {
        [super viewDidLoad];
    
        wasLoaded = NO;
        alertWasShown = NO;
        myWebView.delegate = self;
    }
    
    - (void)webViewDidStartLoad:(UIWebView *)webView {
        // Not necessary to do anything here.
    }
    
    - (void)webViewDidFinishLoad:(UIWebView *)webView {
        wasLoaded = YES; // Indicates that it finished loading.
    }
    
    - (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
        if (alertWasShown == NO) {
            UIAlertView *alert = ... // Create an alert.
            [alert show];
    
            alertWasShown = YES;
        }
    }
    

    I hope that helps.

提交回复
热议问题