Reputation: 87
I want that the webview in my application refreshes every time the app becomes active (starting via homescreen or double tap on the home-button).
My ViewController.m looks like this:
- (void)viewDidLoad
{
NSURL *url = [NSURL URLWithString:@"http://cargo.bplaced.net/cargo/apptelefo/telefonecke.html"];
NSURLRequest *req = [NSURLRequest requestWithURL:url];
[_webView loadRequest:req];
[super viewDidLoad];
}
- (void)viewDidAppear:(BOOL)animated{
[super viewDidAppear:animated];
[_webView reload];
}
-(BOOL) webView:(UIWebView *)inWeb shouldStartLoadWithRequest:(NSURLRequest *)inRequest navigationType:(UIWebViewNavigationType)inType {
if ( inType == UIWebViewNavigationTypeLinkClicked ) {
[[UIApplication sharedApplication] openURL:[inRequest URL]];
return NO;
}
return YES;
}
Whats wrong with this code? Thanks in advance!
Upvotes: 0
Views: 2098
Reputation: 3772
I don't think viewDidAppear:
will fire when the app gains foreground; these viewWill* and viewDid* methods are for view transitions (modal, push) and not anything to do with the app lifecycle events.
What you will want to do is to register for foreground events specifically and refresh the webview when you receive the notification. You will register for the notifications in your viewDidAppear:
method and de-register them in your viewDidDisappear:
method. You do this so that your controller, if and when it disappears, won't continue to reload the webview (or attempt to reload a zombie instance and crash) when it's not displaying anything to the user. Something like the following should work:
- (void)viewDidAppear:(BOOL)animated{
[super viewDidAppear:animated];
[_webView reload]; // still want this so the webview reloads on any navigation changes
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(willEnterForeground) name:UIApplicationWillEnterForegroundNotification object:nil];
}
- (void)viewDidDisappear:(BOOL)animated{
[super viewDidDisappear:animated];
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationWillEnterForegroundNotification object:nil];
}
- (void)willEnterForeground {
[_webView reload];
}
Upvotes: 3