iOS - 将特定于分发资源路径的图像复制到Documents Dir

时间:2013-09-23 16:17:35

标签: ios objective-c xcode resourcebundle

我正在尝试从应用程序启动时从bundle resourcePath中获取所选文件。我能够获取资源路径中的所有文件,但是当我尝试获取名称存储在BGImage.plist中的文件时,我收到错误“cocoa 260”(在指定路径找不到项目)。

但是路径中存在图像,我可以通过[fileManager 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中存储名称?

1 个答案:

答案 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];
    }];
}
相关问题