【发布时间】:2012-05-16 21:38:15
【问题描述】:
我想在用户连接到网络时加载网页并离线存储(包括图像/资源)。如果用户没有连接到任何网络,那么我应该加载以前存储的网页。我试过NSData dataWithContentsOfURL:(NSURL *)url 和NSString stringWithContentsOfURL 但这些商店只存储html 内容而不是资源。
提前致谢。
【问题讨论】:
我想在用户连接到网络时加载网页并离线存储(包括图像/资源)。如果用户没有连接到任何网络,那么我应该加载以前存储的网页。我试过NSData dataWithContentsOfURL:(NSURL *)url 和NSString stringWithContentsOfURL 但这些商店只存储html 内容而不是资源。
提前致谢。
【问题讨论】:
您可以使用ASIHttpRequest 做到这一点。如果您不想使用该项目(它不再处于活动状态),您可以查看代码及其作用。查看“how to cache a whole web page with images in iOS”了解更多信息。
【讨论】:
我不知道是否有像 myWebView.cache4Offline = YES; 这样的单行解决方案,但我担心只要您无法访问网站的代码(即,如果您想制作 any em> 网站可在您的应用程序中离线使用),您必须自行编程。仔细想想,好像没那么难:
NSData dataWithContentsOfURL 从 Internet 下载这些资源(可能有点烦人,因为相对/绝对 URL)希望对你有帮助
【讨论】:
将此数据写入文件使用:
-(void)writeDataToFile:(NSString*)filename
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
if(filename==nil)
{
DLog(@"FILE NAME IS NIL");
return;
}
// the path to write file
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat: @"%@",filename]];
/*NSData *writeData;
writeData=[NSKeyedArchiver archivedDataWithRootObject:pArray]; */
NSFileManager *fm=[NSFileManager defaultManager];
if(!filePath)
{
//DLog(@"File %@ doesn't exist, so we create it", filePath);
[fm createFileAtPath:filePath contents:self.mRespData attributes:nil];
}
else
{
//DLog(@"file exists");
[self.mRespData writeToFile:filePath atomically:YES];
}
NSMutableData *resData = [[NSMutableData alloc] init];
self.mRespData=resData;
[resData release];
}
下次再加载。
【讨论】:
我认为简单的解决方案是这样的——《Safari 客户端存储和离线应用程序编程指南》,https://developer.apple.com/library/archive/documentation/iPhone/Conceptual/SafariJSDatabaseGuide/Introduction/Introduction.html
仅当您正在使用 HTML5 和 webview 制作应用时,目前尚未测试此方法,因此它可能会起作用。
【讨论】: