2013-04-06 59 views
3

我想刷新一個UIWebView,每當我的應用程序來到前臺。我真正在ViewController.m中有一個檢查互聯網訪問(hasInternet)和viewDidLoad的方法。如何在應用程序進入前臺時刷新UIWebView?

#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 

有關如何啓用此功能的任何建議?它是在AppDelegate中進行還是在ViewController.m中創建另一個方法?

+0

只有使用[tag:Xcode]標籤才能瞭解關於IDE本身的問題。謝謝! – Undo 2013-04-07 01:42:28

回答

0

註冊UIApplicationDidBecomeActiveNotification或UIApplicationWillEnterForegroundNotification。

+0

我該如何註冊?我是新來的ios和xcode。你有推薦的教程嗎? – sharataka 2013-04-06 18:46:03

+0

它是UIApplication類文檔中列出的通知(NSNotification)。 – matt 2013-04-06 18:48:08

+0

如果您不知道通知是什麼,您可以閱讀我的書中解釋它的部分:http://www.apeth.com/iOSBook/ch11.html#_notifications – matt 2013-04-06 18:49:05

8

你應該註冊一個UIApplicationWillEnterForegroundNotificationViewControllerviewDidLoad方法,每當應用程序從後臺回來,你可以做任何你想做的通知註冊的方法來做。當應用從背景回到前景時,ViewControllerviewWillAppearviewDidAppear不會被調用。

-(void)viewDidLoad{ 

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(doYourStuff) 

    name:UIApplicationWillEnterForegroundNotification object:nil]; 
} 

-(void)doYourStuff{ 

    [webview reload]; 
} 

不要忘記取消註冊您註冊的通知。

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

請注意,如果您註冊viewControllerUIApplicationDidBecomeActiveNotification那麼你的方法將每次你的應用程序被激活調用,它不會是適當的,爲這個註冊通知。

相關問題