UIWebView没有刷新

时间:2012-11-25 14:10:10

标签: objective-c ios uiwebview webview refresh

我希望每次应用程序变为活动状态时,我的应用程序中的webview都会刷新(从主屏幕开始或双击主页按钮)。

我的ViewController.m看起来像这样:

- (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;
}

这段代码有什么问题?提前谢谢!

1 个答案:

答案 0 :(得分:3)

当应用程序获得前景时,我认为viewDidAppear:不会触发;这些viewWill *和viewDid *方法用于视图转换(模态,推送),而不是与应用程序生命周期事件有关。

您要做的是专门注册前台事件,并在收到通知时刷新Webview。您将使用viewDidAppear:方法注册通知,并在viewDidDisappear:方法中取消注册。你这样做是为了让你的控制器,如果它消失了,当它没有向用户显示任何内容时,将不会继续重新加载webview(或尝试重新加载一个僵尸实例并崩溃)。以下内容应该有效:

- (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];
}