如何在UIWebView中缓存内容以便稍后加载? [英] How to cache content in UIWebView for faster loading later on?
问题描述
我注意到iphone safari会缓存内容,以便稍后加载页面的速度要快得多,就像桌面浏览器一样。因此,以移动gmail网页为例,第一次加载非常慢(5-10秒)。但是,如果我关闭标签并重新打开页面,则非常快(1秒)。
但是,如果您通过a加载内容,则此行为不一样UIWebView在您的应用程序。我错过了一些设置?如何让UIWebView自动缓存内容,而无需亲自保存内容?
解决方案关键是: 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发布];
}
[连接释放];
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 first load is quite slow (5-10 secondS). But if I close the tab and reopen the page again, it's very quick (1 second).
However, this behavior is not the same if you load the content through a UIWebView in your app. Am I missing some settings? How do I make the UIWebView cache the content automatically without going through the hassle of saving the content myself?
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];
这篇关于如何在UIWebView中缓存内容以便稍后加载?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!