UIWebView does not load HTTPS Page: Error Domain=NSURLErrorDomain Code=-999 “The operation couldn’t be completed. (NSURLErrorDomain error -999.)”

情到浓时终转凉″ 提交于 2019-12-04 22:54:26

I ran your code. It worked fine approximately 50% of the time, and showed the -999 error the other times.

That error code is NSURLErrorCancelled, as per URL Loading System Error Codes in Apple's Foundation Constants Reference. So something is cancelling the page load.

I printed the page content that was received, using this:

println(aWebView.stringByEvaluatingJavaScriptFromString("document.body.innerHTML"));

I see that the Javascript in the page contains this:

if (mobilePath) {
   document.body.style.display = 'none';
   document.location = mobilePath;  
}

My guess is that this Javascript starts to run as soon as the content is loaded. This results in a race condition where sometimes the page is immediately redirected to a different document.location, and so the first page load is cancelled before it loads completely.

You should change the server so that it does not send this Javascript.

Alternatively, if you just want to load the website like a normal website, then you can let UIWebView handle the redirects for you. In the case of this site, I got it working properly by setting the User-agent to pretend to be mobile Safari. I also removed shouldStartLoadWithRequest because it was only interfering with things.

override func viewDidAppear(animated: Bool) {
    super.viewDidAppear(animated)

    var request = NSMutableURLRequest(URL: NSURL(string: urlString)!)
    var userAgent = ["UserAgent": "mozilla/5.0 (iphone; cpu iphone os 7_0_2 like mac os x) applewebkit/537.51.1 (khtml, like gecko) version/7.0 mobile/11a501 safari/9537.53"]
    NSUserDefaults.standardUserDefaults().registerDefaults(userAgent as [NSObject : AnyObject])

    self.webView.loadRequest(request)
  }

If I don't have the code to pretend to be mobile Safari, then the page content loads but it doesn't do the right thing. It just stops at a spinner. I presume that the website is sending different Javascript depending on which rendering engine it thinks it is talking to. If you don't specify any User-agent then you are at the mercy of whatever their web designer has done in terms of specifying the default behavior.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!