1

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

但是图像存在于路径中,我可以通过执行 [fileManager copyItemAtPath:bundlePath toPath:BGImagePath error:nil] 来获取所有图像;

下面的代码不起作用..(参考:iPhone(iOS):将文件从主包复制到文档文件夹错误

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 中存储名称?

4

1 回答 1

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];
    }];
}
于 2013-09-23T17:53:05.083 回答