2012-11-25 68 views
0

我希望每當應用程序變爲活動狀態(通過主屏幕或雙擊主屏幕按鈕時)刷新應用程序中的webview。UIWebView不刷新

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

哪些錯誤與此代碼?提前致謝!

回答

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]; 
} 
+0

感謝您的解決方案。這是完美的。 –