2013-09-23 33 views
1

我试图在应用程序启动时从bundle resourcePath中获取选定文件。我能够获取资源路径中的所有文件,但是当我尝试使用存储在BGImage.plist中的名称获取文件时,出现错误“cocoa 260”(找不到指定路径中的项目)。iOS - 将特定图像从束资源路径复制到文档目录

但是图像出现在路径上,我可以通过[文件管理器copyItemAtPath:bundlePath toPath:BGImagePath error:nil]获取所有图像;

下面的代码不工作。(参考:iPhone (iOS): copying files from main bundle to documents folder error

NSString* BGImagePath =[[[AppDelegate applicationDocumentsDirectory] 
         URLByAppendingPathComponent:@"BGImages" isDirectory:YES] 
         path]; 
NSFileManager* fileManager = [NSFileManager defaultManager]; 
NSError *error = nil; 
NSArray *folderContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:BGImagePath error:&error]; 
NSString *bundlePath = [[NSBundle mainBundle] resourcePath]; 
NSString *BundleImagePath = [[[NSBundle mainBundle] bundlePath] stringByAppendingPathComponent:@"BGImages.plist"];   //has file names 
bgImagesArray = [[NSArray arrayWithContentsOfFile:BundleImagePath] retain]; 

if (folderContents.count == 0) { 
    for (id obj in bgImagesArray) { 
      NSError* error; 
      if ([fileManager 
        copyItemAtPath:[bundlePath :obj] 
        toPath:[BGImagePath stringByAppendingPathComponent:obj] 
        error:&error]) 
       NSLog(@" *-> %@", [bundlePath stringByAppendingPathComponent:obj]); 
     } 
    } 
} 

是否有任何其他优雅的方式来获得特定的文件,而无需在存储的plist名字?

+0

如果你在一个“'NSError'”传递的对象,而不是“'nil'”变成“'copyItemAtPath'”的错误参数,你得到一个错误返回给你? bgImagesArray是否实际加载值? –

+0

迈克,问题已经修复。更新了答案。谢谢.. –

回答

1

这下面的代码解决了该问题:

NSFileManager* fileManager = [NSFileManager defaultManager]; 
NSString* bgImagePath =[[[AppDelegate applicationDocumentsDirectory] 
         URLByAppendingPathComponent:@"BGImages" isDirectory:YES] 
         path]; 
[fileManager createDirectoryAtPath:bgImagePath withIntermediateDirectories:NO attributes:nil error:nil]; 
    NSArray * folderContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:bgImagePath error:nil]; 
NSString * bundlePath = [[NSBundle mainBundle] resourcePath]; 
NSString * bundleImagePath = [[NSBundle mainBundle] pathForResource:@"BGImages" ofType:@"plist"]; 
NSArray* bgImagesArray = [NSArray arrayWithContentsOfFile:bundleImagePath]; 
if (folderContents.count == 0) { 
    [bgImagesArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { 
     NSString * sourcePath = [bundlePath stringByAppendingPathComponent:obj]; 
     NSString * destinationPath = [bgImagePath stringByAppendingPathComponent:obj]; 
     [fileManager copyItemAtPath:sourcePath toPath:destinationPath error:nil]; 
    }]; 
} 
相关问题