Индикатор загрузки в веб-просмотре

Мое приложение показывает статьи из RSS-канала в виде таблицы, а затем, когда вы выбираете строку, открывает контроллер веб-представления для отображения статьи. Пытаюсь добавить индикатор загрузки. Если я выберу строку, индикатор отобразится на короткое время, а затем исчезнет до полной загрузки страницы. Кроме того, если я вернусь к просмотру таблицы и выберу другую строку, индикатор загрузки никогда не появится. Я использую настраиваемый индикатор загрузки под названием SVProgressHUD, и он отлично работает в других частях приложения. Но я не думаю, что это проблема. Что я делаю неправильно?

Вот мой метод didSelectRowAtIndexPath в моем табличном представлении:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [[webViewController webView]loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"about:blank"]]];

    [self.navigationController pushViewController:webViewController animated:YES];

    // Grab the selected item
    RSSItem *entry = [[channel items]objectAtIndex:[indexPath row]];

    // Construct a URL with the link string of the item
    NSURL *url = [NSURL URLWithString:[entry link]];

    // Construct a request object with that URL
    NSURLRequest *req = [NSURLRequest requestWithURL:url];

    // Load the request into the web view
    [[webViewController webView]loadRequest:req];
    webViewController.hackyURL = url;
}

Индикатор загрузки запускается на этой строке в viewDidLoad WebViewController:

[SVProgressHUD showWithStatus:@"Loading"];

А вот и мой WebViewController.

#import "WebViewController.h"
#import "TUSafariActivity.h"
#import "SVProgressHUD.h"

@implementation WebViewController
@synthesize webView=webView, hackyURL=hackyURL;

- (void)loadView
{
    // Create an instance of UIWebView as large as the screen
    CGRect screenFrame = [[UIScreen mainScreen]applicationFrame];
    UIWebView *wv = [[UIWebView alloc]initWithFrame:screenFrame];
    webView = wv;
    NSLog(@"%@",webView.request.URL);
    // Tell web view to scale web content to fit within bounds of webview
    [wv setScalesPageToFit:YES];

    [self setView:wv];
}

- (UIWebView *)webView
{ 
    return (UIWebView *)[self view];
}

- (void) showMenu
{
    NSURL *urlToShare = hackyURL;
    NSArray *activityItems = @[urlToShare];
    TUSafariActivity *activity = [[TUSafariActivity alloc] init];

    __block UIActivityViewController *activityVC = [[UIActivityViewController alloc]initWithActivityItems:activityItems applicationActivities:@[activity]];
    activityVC.excludedActivityTypes = @[UIActivityTypeAssignToContact, UIActivityTypePostToWeibo, UIActivityTypeSaveToCameraRoll];

    [self presentViewController:activityVC animated:YES completion:^{activityVC.excludedActivityTypes = nil; activityVC = nil;}];
}

- (void)toggleBars:(UITapGestureRecognizer *)gesture
{
    BOOL barsHidden = self.navigationController.navigationBar.hidden;

    if (!barsHidden)
    {
        [[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:UIStatusBarAnimationSlide];
        [self hideTabBar:self.tabBarController];
    }
    else if (barsHidden)
    {
        [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:UIStatusBarAnimationSlide];
        [self showTabBar:self.tabBarController];
    }

    [self.navigationController setNavigationBarHidden:!barsHidden animated:YES];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.

    [SVProgressHUD showWithStatus:@"Loading"];

    UIBarButtonItem *systemAction = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAction target:self action:@selector(showMenu)];
    self.navigationItem.rightBarButtonItem = systemAction;

    UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(toggleBars:)];
    [webView addGestureRecognizer:singleTap];
    singleTap.delegate = self;

    // self.hidesBottomBarWhenPushed = YES;
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
{
    return YES;
}

- (void) hideTabBar:(UITabBarController *) tabbarcontroller
{
    CGRect screenRect = [[UIScreen mainScreen] bounds];

    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.5];
    float fHeight = screenRect.size.height;
    if(  UIDeviceOrientationIsLandscape([UIApplication sharedApplication].statusBarOrientation) )
    {
        fHeight = screenRect.size.width;
    }

    for(UIView *view in tabbarcontroller.view.subviews)
    {
        if([view isKindOfClass:[UITabBar class]])
        {
            [view setFrame:CGRectMake(view.frame.origin.x, fHeight, view.frame.size.width, view.frame.size.height)];
        }
        else
        {
            [view setFrame:CGRectMake(view.frame.origin.x, view.frame.origin.y, view.frame.size.width, fHeight)];
            view.backgroundColor = [UIColor blackColor];
        }
    }
    [UIView commitAnimations];
}

- (void) showTabBar:(UITabBarController *) tabbarcontroller
{
    CGRect screenRect = [[UIScreen mainScreen] bounds];
    float fHeight = screenRect.size.height - 49.0;

    if(  UIDeviceOrientationIsLandscape([UIApplication sharedApplication].statusBarOrientation) )
    {
        fHeight = screenRect.size.width - 49.0;
    }

    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.5];
    for(UIView *view in tabbarcontroller.view.subviews)
    {
        if([view isKindOfClass:[UITabBar class]])
        {
            [view setFrame:CGRectMake(view.frame.origin.x, fHeight, view.frame.size.width, view.frame.size.height)];
        }
        else
        {
            [view setFrame:CGRectMake(view.frame.origin.x, view.frame.origin.y, view.frame.size.width, fHeight)];
        }
    }
    [UIView commitAnimations];
}

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    //stop the activity indicator when done loading
    [SVProgressHUD dismiss];
}

@end

person raginggoat    schedule 13.08.2013    source источник


Ответы (2)


Вы должны использовать delegate функции webview см. Ниже

-(void)webViewDidStartLoad:(UIWebView *)webView{
   //SHOW HUD
}

-(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{
  //KILL HUD
}

-(void)webViewDidFinishLoad:(UIWebView *)webView{

    if(!webView.loading){
         //KILL HUD
    }
}

В webview обычно происходит кеширование, поэтому HUD может не отображаться долго, поскольку он будет отображаться при первой загрузке.

Надеюсь, это вам поможет.

person iphonic    schedule 13.08.2013
comment
Я попытался реализовать эти методы с помощью UIActivityIndicatorView, и он появляется, но я не могу заставить его остановиться и исчезнуть, когда страница будет загружена. - person raginggoat; 13.08.2013
comment
Я разместил точки останова на этих методах, и похоже, что они даже не вызываются. - person raginggoat; 14.08.2013

Это исправлено. Мне просто нужно было добавить

webView.delegate = self;
person raginggoat    schedule 14.08.2013