Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I detect an authentication challenge from a UIWebView?

I've seen many questions that ask (and answer) how to supply credentials when you know beforehand that the request requires them.

When I load a site that requests an authentication challenge, (responds with HTTP 401), my UIWebViewDelegate only receives the following callbacks: webView:shouldStartLoadWithRequest:navigationType: and sometimes webViewDidStartLoad: (webViewDidStartLoad: seems to be called if I navigate directly to the site, and it seems not to be called if I'm redirected there).

By overriding -[NSObject respondsToSelector:], the UIWebViewDelegate receives some calls to uiWebView:resource:canAuthenticateAgainstProtectionSpace:forDataSource: and uiWebView:resource:didReceiveAuthenticationChallenge:fromDataSource:, which could be useful, but of course those are private API and will probably get my app rejected.

I've tested a few different mainstream apps with embedded UIWebViews. So far, only Chrome handles these authentication challenges properly. I've even set up my own server and validated that Chrome only POSTs once. Twitter and Tweetbot fail just show the loading screen forever, just like mine.

Is there another (probably very hacky) way to detect these authentication challenges other than using a second speculative NSURLConnection? If I make a POST request, that will double-POST everything, which is bad.

I've added a radar to request an enhancement to UIWebView for this. Please duplicate it.

like image 772
Heath Borders Avatar asked Apr 26 '13 14:04

Heath Borders


2 Answers

Apple now has sample code that solves this problem. It also looks like the most complete documentation of how to implement an NSURLProtocol properly.

like image 172
Heath Borders Avatar answered Nov 03 '22 01:11

Heath Borders


You could load all requests in your own NSURLConnection, then feed the data into the webview as a string. This would allow you to intercept the connection in all its glory and still get the native UIWebView rendering. I’m not sure if it would work well with streaming the data into the web view as it arrives, but hopefully we aren’t talking about too much data here.

like image 32
Jeff Kelley Avatar answered Nov 03 '22 00:11

Jeff Kelley