iOS - 将特定图像从捆绑资源路径复制到 Documents Dir
Posted
技术标签:
【中文标题】iOS - 将特定图像从捆绑资源路径复制到 Documents Dir【英文标题】:iOS - Copy specific images from bundle resource path to Documents Dir 【发布时间】:2013-09-23 16:17:34 【问题描述】:我正在尝试在应用程序启动时从 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 中存储名称?
【问题讨论】:
如果您将“NSError
”对象而不是“nil
”传递给“copyItemAtPath
”的错误参数,您会收到返回错误吗? bgImagesArray 是否真的加载了值?
迈克,问题已解决。更新了答案。谢谢..
【参考方案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];
];
【讨论】:
以上是关于iOS - 将特定图像从捆绑资源路径复制到 Documents Dir的主要内容,如果未能解决你的问题,请参考以下文章
iOS - 将 sqlite 复制到 CoreData 的捆绑包