我试图在应用程序启动时从 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 中存储名称?
最佳答案
以下代码解决了这个问题:
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 - 将特定图像从包资源路径复制到文档目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18964117/