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 proto开发者_如何学Gocol:
- (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.
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!
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.
精彩评论