Monday 30 July 2018

How to get a final URL after t.co redirects in WKWebView

I know that I can generally get the current URL of WKWebView by using the URL property. However I have discovered that when there is a redirect, it will not give me the proper URL.

For example, if I go to http://twitter.com and then click on a link to some other company (ex: http://mycompany.com), then I see a t.co/XXX URL which eventually redirects me to mycompany.com.

However, when I look at WKWebView's URL property, I am seeing "t.co" instead of "mycompany.com".

Strangely, I am never seeing didReceiveServerRedirectForProvisionalNavigation:... called, and when I check URL at didStartProvisionalNavigation:... and decidePolicyForNavigationAction:... I just see the "t.co" URL instead of the "mycompany.com" one.

Also, I will need to know the domain in order to make some adjustments to the body, so I am not sure if I can use JS here.

Please let me know if you have any ideas.

UPDATE: I realized this only happens when I use a custom URL scheme set via setURLSchemeHandler:, which I had omitted from the question originally since I didn't think it was related.

After some playing around, I was able to get things working with the following change in willPerformHTTPRedirection:...:

NSMutableURLRequest *newRequest = 
[NSMutableURLRequest requestWithURL:request.URL];

dispatch_async(dispatch_get_main_queue(), ^{
    [_webView loadRequest:newRequest];
});

 completionHandler(nil);

UPDATE: This has a serious drawback because URLs that are not for the main frame will come into willPerformHTTPRedirection:..., and if the request is re-loaded for all of these the page gets messed up.

I need a way to determine if the URL is from the main frame and only do the reload for those.



from How to get a final URL after t.co redirects in WKWebView

No comments:

Post a Comment