UIWebView内容使用NSURLConnection预加载

时间:2014-01-31 18:26:25

标签: ios uiwebview

我正在开发一款拥有2个VC,mapVC(使用谷歌地图SDK)和webVC的iOS应用。在mapVC上选择注释,然后转换到webVC并打开相应的网页。 但是webView的viewDidLoad中的loadRequest方法太慢而无法等待。

所以我想在mapView上选择一个pin时预加载web数据,然后使用loadData方法将预加载的数据移交给webVC。

但是webVC只显示文本,没有图像没有CSS。 我该怎么做才能预加载完整的HTML / CSS /图像? 任何建议表示赞赏提前谢谢。

我目前的源代码如下。

// --- 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];
}

2 个答案:

答案 0 :(得分:1)

您只加载了HTML代码,但没有加载内容(例如media / images / css)。您必须预先解析响应并手动预加载其余内容。

NSURLConnection不会在响应中查找URL,也不会自动加载

答案 1 :(得分:1)

看看ASIWebPageRequest。它允许下载整个网页,包括所有资源。

相关问题