Search code examples
iosvariablesnsurl

Getting the current webview URL and passing it to another view


Ok, so I am trying to get the current URL of a webView so that I can parse it and isolate a number.. However the variable _webURL isn't being set with the URL. The URL is not printing to the log using the following, why?:

implementation of initial display:

@synthesize adWebView1;
@synthesize webURL = _webURL;

...

- (void)viewDidLoad
{
    [adWebView1 loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://m.web.org/bannercontroller.php"]]];

    _webURL = adWebView1.request.URL.absoluteString;
    NSLog(@"The Current URL is", _webURL);

    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}

- (void)viewDidUnload
{
    adWebView1 = nil;
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

I modified it to:

- (void)viewDidLoad
{
    [adWebView1 loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://m.web.org/bannercontroller.php"]]];

    NSString *rawURL = [adWebView1 stringByEvaluatingJavaScriptFromString:@"location.href;"];

    NSLog(@"Das URL ist", *rawURL);
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}

Is producing the following error:

Cannot pass object with interface type 'NSString' by-value through veriadic function.


Solution

  • You use the request to create the webview, but from there it will no longer use that request, so it might not update the request object.

    The request will start when you create the webview. It will not wait until the request finish so you might need to check if the request is still running.

    to get the url later you can use:

    NSString *rawLocationString = [adWebView1 stringByEvaluatingJavaScriptFromString:@"location.href;"];
    

    I'm not sure if it is available already in viewDidLoad.

    BTW: You should not call URL.absoluteString. While it technically might work it's not correct. absoluteString is a method and not a property, so you should not access it as it would be one.