繁体   English   中英

iPhone(iOS):将文件从主包复制到文档文件夹错误

[英]iPhone (iOS): copying files from main bundle to documents folder error

我试图在首次启动时将我的应用程序包中的一些文件复制到文档目录。 我有第一次启动的检查,但为了清楚起见,它们未包含在代码段中。 问题是我正在复制到文档目录(已经存在),在文档中,它说明:

在操作之前, dstPath不得存在。

对我来说直接复制到文档根目录的最佳方法是什么? 我想这样做的原因是允许iTunes文件共享支持。

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
  NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
  NSString *sourcePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"Populator"];

  NSLog(@"\nSource Path: %@\nDocuments Path: %@", sourcePath, documentsDirectory);

  NSError *error = nil;

  if([[NSFileManager defaultManager] copyItemAtPath:sourcePath toPath:documentsDirectory error:&error]){
    NSLog(@"Default file successfully copied over.");
  } else {
    NSLog(@"Error description-%@ \n", [error localizedDescription]);
    NSLog(@"Error reason-%@", [error localizedFailureReason]);
  }
  ...
  return YES;
}

谢谢

目标路径必须包含要复制的项目的名称,而不仅仅是文档文件夹。 尝试:

if([[NSFileManager defaultManager] copyItemAtPath:sourcePath 
          toPath:[documentsDirectory stringByAppendingPathComponent:@"Populator"]
          error:&error]){
...

编辑:抱歉误解了你的问题。 不知道是否有更好的选择,然后迭代文件夹内容并分别复制每个项目。 如果你的目标是iOS4,你可以使用NSArray的-enumerateObjectsUsingBlock:函数:

NSArray* resContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:copyItemAtPath:sourcePath error:NULL];
[resContents enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop)
    {
        NSError* error;
        if (![[NSFileManager defaultManager] 
                  copyItemAtPath:[sourcePath stringByAppendingPathComponent:obj] 
                  toPath:[documentsDirectory stringByAppendingPathComponent:obj]
                  error:&error])
            DLogFunction(@"%@", [error localizedDescription]);
    }];

PS如果您不能使用块,您可以使用快速枚举:

NSArray* resContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:copyItemAtPath:sourcePath error:NULL];

for (NSString* obj in resContents){
    NSError* error;
    if (![[NSFileManager defaultManager] 
                 copyItemAtPath:[sourcePath stringByAppendingPathComponent:obj] 
                 toPath:[documentsDirectory stringByAppendingPathComponent:obj]
                 error:&error])
            DLogFunction(@"%@", [error localizedDescription]);
    }

一张纸条:
不要在didFinishLaunchingWithOptions中发出冗长的操作:这是一个概念上的错误。 如果这个副本花费太多时间,看门狗会杀了你。 在辅助线程或NSOperation中启动它...我个人使用定时器proc。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM