Unable to display URL in WebView from another view

2019-08-30 18:02发布

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 ?

标签: ios uiwebview
1条回答
\"骚年 ilove
2楼-- · 2019-08-30 19:00

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.
查看更多
登录 后发表回答