当app来到前台时如何刷新UIWebView?

时间:2013-04-06 18:41:17

标签: iphone ios objective-c

每当我的应用程序到达前台时,我想刷新UIWebView。我在ViewController.m中真正拥有的是一种检查互联网访问(hasInternet)和viewDidLoad的方法。

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

@synthesize webview;

-(BOOL)hasInternet{
    Reachability *reach = [Reachability reachabilityWithHostName:@"www.google.com"];
    NetworkStatus internetStats = [reach currentReachabilityStatus];

    if (internetStats == NotReachable) {
        UIAlertView *alertOne = [[UIAlertView alloc] initWithTitle:@"You're not connected to the internet." message:@"Please connect to the internet and restart the app." delegate:self cancelButtonTitle:@"Dismiss" otherButtonTitles:nil];
        [alertOne show];
    }

    return YES;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self hasInternet];
    [webView loadRequest: [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://warm-chamber-7399.herokuapp.com/"]] ];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

有关如何启用此功能的任何建议?它是在AppDelegate中还是在ViewController.m中创建另一个方法?

2 个答案:

答案 0 :(得分:8)

您应该在UIApplicationWillEnterForegroundNotification的{​​{1}}方法中注册ViewController,当应用从后台返回时,您可以在注册通知的方法中执行任何操作。当应用从后台返回到前台时,viewDidLoad的{​​{1}}或ViewController将不会被调用。

viewWillAppear

不要忘记取消注册您注册的通知。

viewDidAppear

注意如果您为-(void)viewDidLoad{ [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(doYourStuff) name:UIApplicationWillEnterForegroundNotification object:nil]; } -(void)doYourStuff{ [webview reload]; } 注册-(void)dealloc { [[NSNotificationCenter defaultCenter] removeObserver:self]; } ,那么每次您的应用变为有效时都会调用您的方法,注册此通知是不合适的。< / p>

答案 1 :(得分:0)

注册UIApplicationDidBecomeActiveNotification或UIApplicationWillEnterForegroundNotification。