I'm currently attempting to download a webpage using a NSURLSession in order to retrieve a status update on the download progress. Unfortunately, after downloading the webpage, when I go to load the webpage, there are visual issues (missing images, missing javascript, missing styles, etc), leaving the webpage looking broken and in complete. When loading directly to the webView, everything loads correctly. I would like to know if there is a way (or anything I'm missing) to download ALL aspects of the webpage and load them up so I may load the full webpage and display a loading bar while the page loads.

   - (void)loadRequest:(NSURLRequest *)request
{
    NSURLSessionConfiguration *sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration];
    self.urlSession = [NSURLSession sessionWithConfiguration:sessionConfig delegate:self delegateQueue:[NSOperationQueue mainQueue]];
    self.downloadTask = [self.urlSession downloadTaskWithRequest:request];
    [self.downloadTask resume];
}

    - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)downloadURL
{
    [_webView loadData:[NSData dataWithContentsOfURL:downloadURL] MIMEType:downloadTask.response.MIMEType textEncodingName:downloadTask.response.textEncodingName baseURL:nil];
}
有帮助吗?

解决方案

I was having similar problems (missing images etc.). You need to provide a baseURL. Try:

[_webView loadData:[NSData dataWithContentsOfURL:downloadURL] MIMEType:downloadTask.response.MIMEType textEncodingName:downloadTask.response.textEncodingName baseURL:downloadTask.response.URL];

其他提示

In order to display a loading bar you have to make some kind of workaround, because you are not able to know the progress of the resources that are being downloaded.

Many apps use tricks, to simulate that there is a loading ongoing. Here is a simple example to ilustrate the idea:

  • Display loading bar with progress 30% for 1 second.
  • If the request did not finish, display progress 90% until the progress finishes
  • When the request finishes, animate progress to 100%.

You can have a look on this open source library to see how it's done. You can do it in a similar way. https://github.com/ninjinkun/NJKWebViewProgress

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top