更改设置时更新 UIWebView



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

使用 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时更新。

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

在视图控制器中,我可以运行:

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

但是当我尝试在应用程序委托中运行相同的内容时,它不会更新:

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    ViewController *vc = [[ViewController alloc]init];
    [vc updateBrowser];
}

(我还在ViewController.h中包括了- (void) updateBrowser;,在AppDelegate.m中包括了#import "ViewController.h"

谢谢。

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

最新更新