Allowing UIWebView to accept self-signed certificates

Transport-level security requirements for iOS have undergone significant changes recently. Indeed, unconfirmed statistics suggest that the introduction of App Transport Security in iOS 9 was responsible for doubling the size of the StackOverflow database overnight and causing NSAllowsArbitraryLoads to be the top trending hashtag on Twitter for several days. *

Accordingly, you'd be forgiven if - when attempting to access a development server over SSL using a UIWebView - you surmise that an error like NSURLConnection/CFURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9813) is related to the ATS requirements. Alas, no matter how many crazy combinations of exclusion clauses you add to your Info.plist (which of course you totally did, before resorting to the sledgehammer that is NSAllowsArbitraryLoads), the issue persists! A search for the error returns many ATS-related articles, but none seem to have the specific error code you are seeing. In frustration, you resolve to downloading the iOS 8.4 SDK and vow to boycott iOS9 and all future releases until the end of time. As you wait smugly for your download to complete, you begin creating a viral Facebook campaign to convince friends and strangers to do the same.

Sure enough, on 8.4 the error still occurs! You quietly delete your new Facebook page and thank the stars that you're up late enough that nobody is likely to have seen it. Realising now that it is likely a UIWebView-specific issue, a solution is not difficult to pin down. Here, I've adapted the ObjC code to a UIWebView subclass for C#/Xamarin, so that you don't have to! 🎉

Yahoo! Self-sign away!

Considerations:
  • Only use this for development purposes, etc. etc.
  • The _failedRequest and _authenticated variables should really be tracked on a per-domain basis. If you need to work across many domains with the same UIWebView, you should make that change. For testing OAuth via ASP.NET Identity, the code is adequate as-is.

* not really, I made those bits up.