How to get Redirected URL
1) Specify that your class conforms to the UIWebViewDelegate protocol (and make sure your WebView's delegate outlet is connected to your view controller):
@interface YourWebsiteViewController : UIViewController <UIWebViewDelegate>
2) Add the following delegate method:
-(void)webViewDidStartLoad:(UIWebView *)webView
{
NSURL *url = [webView.request mainDocumentURL];
NSLog(@"The Redirected URL is: %@", url);
}
Depending on what you're trying to do with this information, you might want to substitute #2 for this method (which will allow you the opportunity to prevent a page from loading):
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
NSURL *url = [request mainDocumentURL];
NSLog(@"The Redirected URL is: %@", url);
// Return YES if you want to load the page, and NO if you don't.
return NO;
}
user1673099
Updated on June 25, 2022Comments
-
user1673099 almost 2 years
I have a URL.when i try to open it in browser, it will redirect to another URL & display the Content. I want that content But i don't get that redirected URL. So, I can't able to display data.
How can i do that programmatically??
e.g. URL which i have : http://www.windpowerengineering.com/?p=11020
& the redirected URL is: http://www.windpowerengineering.com/design/mechanical/blades/bladeless-turbine-converts-wind-into-fluid-power/
I want this redirected URL. How can i get this?
-
user1673099 over 11 yearshow can i get location header programmatically
-
user1673099 over 11 yearsi get urlString as a about:blank
-
user1673099 over 11 yearscan you help me with some code because i didn't get your point like how to get response from request1
-
user1673099 over 11 yearsyes,its work but i want to get redirected url before web-view load & show.
-
user1673099 over 11 yearsi get null as a url for first two/ three times & is there another way to get redirected URL without using webview delegate method? Because i want to display only specific portion of the html.
-
user1673099 over 11 yearsthe delegate method of web-view did finish load call more than one time.
-
J Shapiro over 11 yearsA couple of possible strategies you could implement: 1) Set a property with the initial URL and check to make sure it's not null and different in the delegate before doing anything with the new URL. If it's different, re-set and check the same property so you don't do anything for the subsequent calls to the delegate method.
-
J Shapiro over 11 years2) Use the NSURLRequest to get the HTML content you want (instead of passing it to the UIWebView with
loadRequest:
). You could implement the delegateNSURLConnectionDataDelegate
and capture redirection URLs with the delegate methodconnection:willSendRequest:redirectResponse:
. Once you have your URL string, send it to the UIWebView withloadHTMLString:baseURL:
Check out the selected answer here for the last step: stackoverflow.com/questions/7981083/…