Search code examples
iosuiwebviewios7uiactivityindicatorview

Add an activity indicator on a uiwebview


I have a viewDidLoad which creates a web view and starts an activity indicator. How do I make the activity indicator stop only when the web page appears? How do I add words to the activity indicator like "Loading"?

// Create the UIWebView
UIWebView *webView = [[UIWebView alloc] initWithFrame:self.view.bounds];

[self.view addSubview:webView];

// Start the throbber to check if the user exists
UIActivityIndicatorView *activityView=[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
activityView.center = CGPointMake([self screenWidth] / 2.0, 370.0);
[activityView startAnimating];
activityView.tag = 100;
[self.view addSubview:activityView];

NSString* url = @"http://google.com";
NSURL* nsUrl = [NSURL URLWithString:url];
NSURLRequest* request = [NSURLRequest requestWithURL:nsUrl cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:30];


// Remove activity view
UIView *viewToRemove = [self.view viewWithTag:100];
//[viewToRemove removeFromSuperview];

[webView loadRequest:request];

Solution

  • How do I make the activity indicator stop only when the web page appears?

    Your object can become delegate for webView to listen to -webViewDidFinishLoad delegate method. So:

    - (void)viewDidLoad {
        // Create the UIWebView
        UIWebView *webView = [[UIWebView alloc] initWithFrame:self.view.bounds];
        webView.delegate = self; // Here is the key
        ...
    }
    
    ...
    
    - (void)webViewDidFinishLoad:(UIWebView *)webView {
        [self.view viewWithTag:100].hidden = YES;
    }
    

    You may also implement -webViewDidStartLoad: to show activity indicator instead of showing it in -viewDidLoad method.

    How do I add words to the activity indicator like "Loading"?

    You should create a separate UILabel, there is no way to add text to standard UIActivityIndicatorView