如何刷新UIWebView时,应用程序来到前台?

我想刷新一个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 

有关如何启用此function的任何build议? 它是在AppDelegate中进行还是在ViewController.m中创build另一个方法?

您应该在您的ViewControllerviewDidLoad方法中注册一个UIApplicationWillEnterForegroundNotification ,并且每当应用程序从后台返回时,您都可以在注册通知的方法中执行任何您想要执行的操作。 ViewControllerviewWillAppearviewDidAppear不会被调用,当应用程序从背景回到前台。

 -(void)viewDidLoad{ [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(doYourStuff) name:UIApplicationWillEnterForegroundNotification object:nil]; } -(void)doYourStuff{ [webview reload]; } 

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

 -(void)dealloc { [[NSNotificationCenter defaultCenter] removeObserver:self]; } 

注意,如果你注册你的viewController for UIApplicationDidBecomeActiveNotification那么你的方法将被调用,每当你的应用程序变为活动,这是不适合注册此通知。

注册UIApplicationDidBecomeActiveNotification或UIApplicationWillEnterForegroundNotification。