kinamin
kinamin

Reputation: 127

UIWebView contents preload using NSURLConnection

I'm developing an iOS app that has 2 VCs, mapVC(using google map SDK) and webVC. Selecting an annotation on mapVC, then transition to webVC with corresponding webpage openned. But loadRequest method in viewDidLoad of webView is too slow to wait.

So I want to preload the web data when selecting a pin on mapView, and then hand over the preloaded data to webVC using loadData method.

But webVC displays only text, no images no CSS. What should I do to preload full HTML/CSS/images? any advice appreciated. thanks in advance.

my current source code as follows.

// --- mapViewController ---
- (BOOL)mapView:(GMSMapView *)mapView didTapMarker:(GMSMarker *)marker
{
    NSURL   *url = [NSURL URLWithString:@"(target URL)"];
    NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url
                                cachePolicy:NSURLRequestUseProtocolCachePolicy
                                        timeoutInterval:60.0];
    receivedData = [NSMutableData dataWithCapacity:0];
    NSURLConnection *urlConnection;
    urlConnection = [NSURLConnection connectionWithRequest:urlRequest delegate:self];
    if (!urlConnection) {
        receivedData = nil;
    }
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    [receivedData setLength:0];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [receivedData appendData:data];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    receivedData = nil;
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([[segue identifier] isEqualToString:@"showWeb"]) {
        WebViewController   *webViewController = [segue destinationViewController];
        webViewController.preloadedData = receivedData;
    }
}

// --- webViewController ---    
- (void)viewDidLoad
{
    [super viewDidLoad];
    self.webView.delegate = self;
    [self.webView loadData:self.preloadedData
                  MIMEType:@"text/html"
          textEncodingName:@"utf-8"
                   baseURL:nil];
}

Upvotes: 0

Views: 1914

Answers (2)

Léo Natan
Léo Natan

Reputation: 57060

Take a look at ASIWebPageRequest. It allows the download of the entire web page, including all resources.

Upvotes: 1

Mirko Brunner
Mirko Brunner

Reputation: 2215

You have only loaded the HTML-Code but not the Content (e.g. media / images / css). You must pre parse the Response and manually pre load the rest stuff.

NSURLConnection make no look up for URL´s inside the response and no autoload

Upvotes: 1

Related Questions