2012-10-08 94 views
1

Settings.bundle中,我有一个标识为url_preference的文本输入。当设置被更改时更新UIWebView

使用ViewController.hViewController.m,和我的故事板我有一个UIWebView设置显示从设置的URL:

- (void) updateBrowser { 
    NSString *fullURL = [[NSUserDefaults standardUserDefaults] stringForKey:@"url_preference"]; 
    NSURL *url = [NSURL URLWithString:fullURL]; 
    NSURLRequest *requestObj = [NSURLRequest requestWithURL:url]; 
    [_EmbeddedBrowser loadRequest:requestObj];  
} 

这工作。

但是,如果更改了设置中的URL,则UIWebView不会更新以反映新的URL。

通过禁止应用程序在后台运行,解决了未反映更新的URL的问题。但是,会出现一个新问题:如果“设置”中的URL保留为,则不会保留会话UIWebView只应在url_preference更改时更新。

我一直在尝试使用applicationWillEnterForegroundAppDelegate.m迫使UIWebView重装,但我有麻烦了。

在ViewController中,我可以运行:

- (void)viewDidLoad { 
    [self updateBrowser]; 
} 

但是当我尝试运行在App代表同样的事情时不更新:

- (void)applicationWillEnterForeground:(UIApplication *)application 
{ 

    ViewController *vc = [[ViewController alloc]init]; 
    [vc updateBrowser]; 
} 

(我还包括- (void) updateBrowser;ViewController.h,并且#import "ViewController.h"AppDelegate.m

谢谢。

回答

2
- (void)viewDidLoad 
{ 
    [self updateBrowser]; 
    [super viewDidLoad]; 
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter]; 
    [center addObserver:self 
       selector:@selector(defaultsChanged:) 
        name:NSUserDefaultsDidChangeNotification 
       object:nil]; 
} 

- (void)defaultsChanged:(NSNotification *)notification { 
    [self updateBrowser]; 
} 

- (void) updateBrowser { 

    NSString *fullURL = [[NSUserDefaults standardUserDefaults] stringForKey:@"url_preference"]; 
    NSURL *url = [NSURL URLWithString:fullURL]; 
    NSURLRequest *requestObj = [NSURLRequest requestWithURL:url]; 
    [_EmbeddedBrowser loadRequest:requestObj]; 

} 

幸运的是,这种情况下不需要使用AppDelegate。实际上有一个通知,您在默认设置更改时收听。您必须将ViewController设置为观察者,并且每次发送NSUserDefaultsDidChangeNotification时都会执行一个函数。每次在设置中更改应用的默认设置时,此通知都会自动发生。这样,每当应用程序进入前台时都不必刷新,只有在设置更改时才会刷新。

+0

非常感谢你,马特!这很棒! – bookcasey

相关问题