Ethan Allen
Ethan Allen

Reputation: 14835

Mac Programming Question: How do I detect the URL of a redirect in a WebView?

This is a MacOS programming question, not iOS (iPhone) programming.

I have a WebView. I can load webpages into the WebView and detect that initial load with this delegate protocol:

- (void)webView:(WebView *)webView decidePolicyForNavigationAction:(NSDictionary *)actionInformation request:(NSURLRequest *)request frame:(WebFrame *)frame decisionListener:(id)listener { NSString *urlString = [[request URL] absoluteString];
NSLog(@"%@", urlString); }

But the page I send it redirects immediately, and I need to see the URL that it redirects to. Unfortunately this protocol just isn't catching the redirect.

Anyone know how to detect the URL of a redirect in a WebView?

Thanks.

Upvotes: 2

Views: 3198

Answers (2)

ughoavgfhw
ughoavgfhw

Reputation: 39905

The webView:decidePolicyForNavigationAction: method is part of the WebPolicyDelegate protocol. There are two ways to do this. If you only want to know when a redirect is happening, you can use webView:didReceiveServerRedirectForProvisionalLoadForFrame: from the WebFrameLoadDelegate Protcol:

- (void)webView:(WebView *)webView didReceiveServerRedirectForProvisionalLoadForFrame:(WebFrame *)frame {
    NSLog(@"%@",[[[[frame provisionalDataSource] request] URL] absoluteString]);
}

If you want to modify the redirect, use webView:resource:willSendRequest:redirectResponse:fromDataSource: from the WebResourceLoadDelegate protocol:

- (NSURLRequest *)webView:(WebView *)sender resource:(id)identifier willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)redirectResponse fromDataSource:(WebDataSource *)dataSource {
    NSURLRequest *request = redirectResponse;
    //make any changes to and return new request
    return request;
}

Whichever way you do it, make sure you set the proper delegate on the webView in order to get the methods called.

Upvotes: 4

user531461
user531461

Reputation:

You're a lucky guy. I've come accross the same problem an hour ago.

According to the WebView reference class in the Apple documentation, you have to set a delegate that conforms to the webframeloaddelegate protocol.

[webView setFrameLoadDelegate:object];

Then in object, you have to set this method:

- (void)webView:(WebView *)sender willPerformClientRedirectToURL:(NSURL *)URL delay:(NSTimeInterval)seconds fireDate:(NSDate *)date forFrame:(WebFrame *)frame 

That's all!

Upvotes: 4

Related Questions