如何将我的文件写入NSBundle?

时间:2012-07-07 08:56:00

标签: iphone ios ipad ios4 nsbundle

我正在编写一个iPhone / iPad应用程序,其中包含压缩文件,其中基本上是网站的内容,然后我可以在提取时运行。 但是我想将所有这些文件和文件夹放在一个文件中,即NSBundle文件,这样我就可以将它显示给用户,就像它是一个文件一样,然后可以删除或移动它但不是走过。 (我的应用程序允许遍历NSDocuments文件夹中的文件夹)

我知道您可以轻松地将自己的NSBundle导入到项目中,然后将其读入网站。 但是,是否可以使用已经制作的目录结构编写一个文件和文件夹,文件和文件夹必须保持不变,即我之前描述的Web文件夹?

如果不是NSBundle,我可以将文件夹写入(转换)到任何其他类型的包中吗?

如果没有,你对我的困境有任何其他建议

1 个答案:

答案 0 :(得分:2)

这不是您问题的直接答案,而是另一种查看问题的方法。

  1. 具体来说,您已声明您的应用允许遍历NSDocumentDirectory中的文件夹。由于您的代码是枚举文件/文件夹的代码,因此您可以简单地实现枚举代码,以便将与某些模式匹配的文件夹(例如* .bundle)视为层次结构中的叶节点;用户永远不知道里面有什么东西。

  2. 更进一步,您可以将.zip文件直接存储在文档目录中,然后在请求访问各个URL时直接将其内容提供给UIWebView。

    可以注册NSURLProtocol的子类,它会在检查所有URL请求时获得第一次破解。如果子类说它可以处理特定的URL(例如,对于特定的主机或路径),那么将创建子类的实例并要求它提供内容。

    此时,您可以使用一些zip读取代码,例如Objective-Zip来从zip中读取所请求的文件,并从请求中返回其内容。

    使用NSURLProtocol +registerClass:向系统注册子类。

    在以下示例中,我的协议处理程序忽略除我网站的请求之外的所有请求。对于那些它返回相同的硬编码字符串(作为概念证明):

    <强> MyURLProtocolRedirector.h

    #import <Foundation/Foundation.h>
    
    @interface MyURLProtocolRedirector : NSURLProtocol
    + (BOOL)canInitWithRequest:(NSURLRequest *)request;
    + (NSURLRequest *)canonicalRequestForRequest:(NSURLRequest *)request;
    - (void)startLoading;
    - (void)stopLoading;
    @end
    

    <强> MyURLProtocolRedirector.m

    #import "MyURLProtocolRedirector.h"
    
    @implementation MyURLProtocolRedirector
    
    + (BOOL)canInitWithRequest:(NSURLRequest *)request {
      if ([request.URL.host compare:@"martinkenny.com"] == 0) {
        return YES;
      }
      return NO;
    }
    
    + (NSURLRequest *)canonicalRequestForRequest:(NSURLRequest *)request {
      return request;
    }
    
    - (void)startLoading {
      NSURLResponse *response = [[NSURLResponse alloc] initWithURL:self.request.URL MIMEType:@"text/plain" expectedContentLength:11 textEncodingName:nil];
      [self.client URLProtocol:self didLoadData:[[NSData alloc] initWithBytes:"Hello World" length:11]];
      [self.client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageAllowed];
      [self.client URLProtocolDidFinishLoading:self];
    }
    
    - (void)stopLoading {
    }
    
    @end
    

    <强> SomeViewController.m

    // register the new URL protocol handler with the system
    [NSURLProtocol registerClass:[MyURLProtocolRedirector class]];
    
    UIWebView *webView = [[UIWebView alloc] initWithFrame:self.view.bounds];
    [webView loadRequest:[[NSURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://www.seenobjects.org/"]]];
    [self.view addSubview:webView];