1

Settings.bundle中,我有一个带有标识符的文本输入url_preference

使用ViewController.h,ViewController.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更改时才应更新。

我一直在尝试使用applicationWillEnterForegroundinAppDelegate.m来强制UIWebView重新加载,但是我遇到了麻烦。

在 ViewController 中,我可以运行:

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

但是当我尝试在 App Delegate 中运行相同的东西时它不会更新:

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

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

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

谢谢你。

4

1 回答 1

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 时执行一个函数。每次在设置中更改应用程序的默认设置时,都会自动出现此通知。这样,您不必每次应用程序进入前台时都刷新,只有在设置更改时才需要刷新。

于 2012-10-08T02:06:08.383 回答