【问题标题】:How to cache entire webpage in iphone?如何在iphone中缓存整个网页?
【发布时间】:2012-05-16 21:38:15
【问题描述】:

我想在用户连接到网络时加载网页并离线存储(包括图像/资源)。如果用户没有连接到任何网络,那么我应该加载以前存储的网页。我试过NSData dataWithContentsOfURL:(NSURL *)urlNSString stringWithContentsOfURL 但这些商店只存储html 内容而不是资源。 提前致谢。

【问题讨论】:

    标签: iphone ios uiwebview


    【解决方案1】:

    您可以使用ASIHttpRequest 做到这一点。如果您不想使用该项目(它不再处于活动状态),您可以查看代码及其作用。查看“how to cache a whole web page with images in iOS”了解更多信息。

    【讨论】:

      【解决方案2】:

      我不知道是否有像 myWebView.cache4Offline = YES; 这样的单行解决方案,但我担心只要您无法访问网站的代码(即,如果您想制作 any em> 网站可在您的应用程序中离线使用),您必须自行编程。仔细想想,好像没那么难:

      1. 扫描 html 字符串以获取图片网址(以及您需要的所有其他内容)
      2. 使用 NSData dataWithContentsOfURL 从 Internet 下载这些资源(可能有点烦人,因为相对/绝对 URL)
      3. 使用 NSData writeToFile:options:error: 将数据保存到文件中:
      4. 将 HTML 中的 URL 替换为 3 中的 filePath。(或者,更好地使用约定来转换 your 文件 URL 中的 their URL)

      希望对你有帮助

      【讨论】:

      • 这个解决方案可以工作,除了你无法用 hTML 中的文件路径替换 URL,因为 filePath 指向 NSData 而不是 .png 图像
      【解决方案3】:

      将此数据写入文件使用:

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

      下次再加载。

      【讨论】:

      • 我认为这不能回答问题。这不是关于如何存储数据,而是关于如何下载网站的所有内容并存储它。
      • 我不想存储任何数据,但发问者似乎...问题 - 据我了解 - 是:如何保存 everything任何 网站供以后离线使用。
      【解决方案4】:

      我认为简单的解决方案是这样的——《Safari 客户端存储和离线应用程序编程指南》,https://developer.apple.com/library/archive/documentation/iPhone/Conceptual/SafariJSDatabaseGuide/Introduction/Introduction.html

      仅当您正在使用 HTML5 和 webview 制作应用时,目前尚未测试此方法,因此它可能会起作用。

      【讨论】:

      • 这是关于离线存储的,如果您是 Web 开发人员,但问题是如何存储 任何 个网站以供离线使用。
      • 谢谢你告诉我,你是对的,只有当我们同时做一个带有 webview 和 HTML5 的应用程序时,HTML5 才能完成这项工作。
      猜你喜欢
      • 2014-07-19
      • 2011-10-05
      • 2012-09-15
      • 2013-05-17
      • 1970-01-01
      • 2016-11-12
      • 2010-11-12
      • 1970-01-01
      • 2021-06-06
      相关资源
      最近更新 更多