iOS UIWebView 不接受 URL 改变

iOS UIWebView not accepting URL changing

我的 UIWebView 有一个奇怪的问题,它不接受任何更改。

当我启动应用程序时,它完美地加载了 URL,委托方法被触发,但 UIWebView 之后不接受任何操作,比如隐藏它或更改它 URL.当我调用 [webView loadRequest:urlRequest]; 将当前 URL 更改为另一个时,委托方法被触发但 WebView 继续查看旧页面,没有变化(仅指示器显示几秒钟然后日志命令在webViewDidStartLoadwebViewDidFinishLoad 以及 shouldStartLoadWithRequest 工作正常)。

场景如下:

- (void)viewDidLoad
{
    [super viewDidLoad];

    NSLog(@"viewDidLoad");

    NSString *urlString = @"http://old.example.com";
    NSURL *url = [NSURL URLWithString:urlString];
    NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
    [webView loadRequest:urlRequest];

    // For here, everything is fine, the WebView loads the OLD URL

    webView.delegate = self;
    webView.opaque = NO;
    webView=[[UIWebView alloc]init];
    [webView setBackgroundColor:[UIColor grayColor]];
    [webView setDelegate:(id<UIWebViewDelegate>)self];
    [self.view addSubview:webView];

    activityIndicator = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    activityIndicator.frame = CGRectMake(200.0, 200.0, 100.0, 40.0);
    activityIndicator.center = self.view.center;
    [self.view addSubview: activityIndicator];

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(loadNotificationUrl:)
                                                 name:@"loadNotificationUrl" object:nil];

}

-(void)loadNotificationUrl:(NSNotification*) notification
{
    // Now the notification arrives holding the NEW URL
    NSDictionary* userInfo = notification.userInfo;
    NSString* NotificationUrl = (NSString*)userInfo[@"url"];
    NSLog (@"Successfully received: %@", NotificationUrl); // it gets --> "http://new.example.com"

    NSURL *url = [NSURL URLWithString:NotificationUrl];
    NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
    NSLog(@"Before Load: %@", [webView stringByEvaluatingJavaScriptFromString:@"window.location.href"]); // --> this is showing "about:blank"!!

    [webView loadRequest:urlRequest]; // This works but doesn't change anything in the WebView! OLD page still showing.


}

谁能告诉我我错过了什么?

初始请求加载到与未来请求不同的 Web 视图中。如果你查看你的代码,你有 [webView loadRequest:urlRequest];

再往下几行,您有 webView=[[UIWebView alloc]init];webView 变量设置为新的 UIWebView 实例,然后将其添加到您的视图中。但是此 Web 视图不可见,因为它的框架大概是 CGRectZero。委托方法正在触发,因为您已将新实例的委托设置为 self,但您还是看不到结果。

删除 webView=[[UIWebView alloc]init];,假设您已在别处初始化 Web 视图,事情可能会如您所愿。

loadRequest:urlRequest之后,您创建了一个新的UIWebView,它覆盖了旧的webView,请将其删除。

移动这一行:

webView=[[UIWebView alloc]init];

在这一行之前:

[webView loadRequest:urlRequest];

在这个方法中:

viewDidLoad

删除 webView = [UIWebView alloc]init];应该工作