How to cache content in UIWebView for faster loading later on?

后端 未结 4 960
醉话见心
醉话见心 2020-11-27 15:02

I notice that the iphone safari caches content so that your page load for later is much faster much like a desktop browser. So take mobile gmail web page for example, the fi

相关标签:
4条回答
  • 2020-11-27 15:14
    NSString *stringurl=[NSString stringWithFormat:@"http://www.google.com"];
    NSURL *url=[NSURL URLWithString:stringurl];
    NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:15.0];
    [uiwebview loadRequest:theRequest];
    

    It will load a url first time then looks for for only the content changes..,if there is no updates in the url content it will load from the cache(local storage).

    0 讨论(0)
  • 2020-11-27 15:21

    Based on this discussion thread it would appear there isn't any OS-level caching possible with UIWebView. Based on experience I've noticed that Safari on my iPhone OS device doesn't cache its web pages (e.g., hitting the back button in Safari does not reload the old page from a cache).

    0 讨论(0)
  • 2020-11-27 15:26

    I've done a couple of apps that cache pages to the Documents folder, then compare the time-stamps of the cached & web pages before loading the new web page. So the basic flow is:

    if (fileIsInCache)
        if (cacheFileDate > webFileDate)
            getCachedFile
        else
            getFileFromWeb
            saveFileToCache
    else
        getFileFromWeb
        saveFileToCache
    
    stuffFileIntoUIView
    
    maybeReduceCache
    

    You still have to hit the web to get the headers, but that's typically much faster than downloading a whole page/image/file.

    0 讨论(0)
  • 2020-11-27 15:30

    The key is: NSURLRequestReturnCacheDataElseLoad

    NSData *urlData;
    NSString *baseURLString =  @"mysite.com";
    NSString *urlString = [baseURLString stringByAppendingPathComponent:@"myfile"];
    
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString] cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval: 10.0]; 
    NSURLConnection *connection=[[NSURLConnection alloc] initWithRequest:request delegate:nil]; 
    
    if (connection)
    { 
        urlData = [NSURLConnection sendSynchronousRequest: request];
    
        NSString *htmlString = [[NSString alloc] initWithData:urlData encoding:NSUTF8StringEncoding];
        [webView loadHTMLString:htmlString baseURL:baseURLString];
        [htmlString release];
    }
    
    [connection release];
    
    0 讨论(0)
提交回复
热议问题