Unable to display URL in WebView from another view controller

|▌冷眼眸甩不掉的悲伤 提交于 2020-01-07 04:55:14

问题


I have a UITableViewController that needs to open a web view.

In my function I have:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{

                LinkViewController *linkViewController = [[LinkViewController alloc] initWithNibName:@"LinkViewController_iPhone" bundle:nil];

                [linkViewController.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.google.com"]]];

                [self.navigationController pushViewController:linkViewController animated:YES];

}

I have connected all outlets and am not getting any warnings however I do not see the page pull up.

However if I go in the actual LinkViewController file and do something like:

- (void)viewDidLoad
{
    [super viewDidLoad];

        NSString *urlAddress = @"http://www.google.com";

    //Create a URL object.
    NSURL *url = [NSURL URLWithString:urlAddress];

    //URL Requst Object
    NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];

    //Load the request in the UIWebView.
    [self.webView loadRequest:requestObj]; 
}

everything seems fine. I do not understand why ?


回答1:


You should add a URL property to your LinkViewController. Then in your table view controller you do this:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    LinkViewController *linkViewController = [[LinkViewController alloc] initWithNibName:@"LinkViewController_iPhone" bundle:nil];             
    linkViewController.URL = [NSURL URLWithString:@"http://www.google.com"];

    [self.navigationController pushViewController:linkViewController animated:YES];
}

Now in your LinkViewController you do:

- (void)viewDidLoad {
    [super viewDidLoad];

    //URL Requst Object
    NSURLRequest *requestObj = [NSURLRequest requestWithURL:self.URL];

    //Load the request in the UIWebView.
    [self.webView loadRequest:requestObj]; 
}

There are two problems with what you had originally:

  1. In the table view controller, you were accessing the webView property before it was initialized. This is why nothing happened.
  2. You were exposing far too much implementation detail of the LinkViewController to the outside world. If you use LinkViewController in many places in your app, you are requiring every user of the class to know to create a URL, create a request, and then tell the internal web view to start loading. All of that logic belongs inside the LinkViewController. Now each user of the class only needs to know to set a simple URL property.


来源:https://stackoverflow.com/questions/15180498/unable-to-display-url-in-webview-from-another-view-controller

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!