How to reload a UIWebView on HomeButton press

2019-08-26 20:42发布

I want to reload a simple UIWebView I have loaded when the app opens and closes from the iPad Home Button.

I've searched other questions, but none seem to fit as I don't want an extra button or Tab or something else in my app.

I tried:

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [webView reload];
}

but this doesn't react. My initialization code is in a controller derived from UIViewController and the UIwebview is initialized in - (void)viewDidLoad

Any clue how to do this?

Kind regards

3条回答
做个烂人
2楼-- · 2019-08-26 21:16

Try refreshing your view in applicationWillEnterForeground:. This message is sent to your application delegate when the application resumes after having been put in the background with the home button.

查看更多
对你真心纯属浪费
3楼-- · 2019-08-26 21:19

Do you mean you want to refresh the web view when the user resumes the app after multitasking? In that case, what you're after is the applicationWillEnterForeground: method in your UIApplicationDelegate.

General information on multitasking is here.

查看更多
不美不萌又怎样
4楼-- · 2019-08-26 21:29

As people have pointed out you probably want the applicationWillEnterForeground: call but don't be tempted to add a load of junk to your app delegate.

Instead - you should register to receive this notification when you init the UIViewController that contains the UIWebView.

- (id)init
{
  self = [super init];
  if (self) {
    [[NSNotificationCenter defaultCenter] addObserver:self 
                                             selector:@selector(reloadWebView:) 
                                                 name:UIApplicationWillEnterForegroundNotification 
                                               object:nil];
    // Do some more stuff
  }
  return self;
}

Then implement the refresh method something like:

- (void)reloadWebView:(NSNotification *)notification
{
  [webView reload];
}

You will need to unregister in your dealloc to avoid any nasty suprises something like this

- (void)dealloc
{
  [[NSNotificationCenter defaultCenter] removeObserver:self];
  [super dealloc];
}
查看更多
登录 后发表回答