有没有办法在iOS上的documents文件夹中使用NSBundle
?
答案 0 :(得分:8)
不确定确切的问题是什么,但这里是我如何访问我的应用程序的本地文档文件夹(这不是您存储应用程序使用的源的文档文件夹,但是您的应用程序存储本地资源的文件夹)
例如,在我的应用程序中,我使用相机拍摄照片并将它们存储到应用程序的本地文件夹,而不是设备相机胶卷,因此要获得我执行此操作的图像数量,请使用viewWillAppear
方法:
// create the route of localDocumentsFolder
NSArray *filePaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
//first use the local documents folder
NSString *docsPath = [NSString stringWithFormat:@"%@/Documents", NSHomeDirectory()];
//then use its bundle, indicating its path
NSString *bundleRoot = [[NSBundle bundleWithPath:docsPath] bundlePath];
//then get its content
NSArray *dirContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:bundleRoot error:nil];
// this counts the total of jpg images contained in the local document folder of the app
NSArray *onlyJPGs = [dirContents filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"self ENDSWITH '.JPG'"]];
// in console tell me how many jpg do I have
NSLog(@"numero de fotos en total: %i", [onlyJPGs count]);
// ---------------
如果您想知道文档文件夹中的内容(您可以在iOS模拟器中实际浏览的那个文件夹
通过〜/ YourUserName / Library / Application Support / iPhone 模拟器/ versioOfSimulator /应用/ appFolder /文件)
您可以使用NSString *bundleRoot = [[NSBundle mainBundle] bundlePath];
代替。
希望它可以帮助你,交配!
答案 1 :(得分:1)
我不完全确定你会得到什么,但是使用应用程序包中的文件的一般方法是将其复制到文档目录中,如下所示:
检查(首次启动,启动或根据需要)文档目录中是否存在文件。
如果不存在,请将文件夹中的“安装”版本复制到文档目录中。
就某些示例代码而言,我使用的方法用于以下目的:
- (BOOL)copyFromBundle:(NSString *)fileName {
BOOL copySucceeded = NO;
// Get our document path.
NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentPath = [searchPaths objectAtIndex:0];
// Get the full path to our file.
NSString *filePath = [documentPath stringByAppendingPathComponent:fileName];
NSLog(@"copyFromBundle - checking for presence of \"%@\"...", fileName);
// Get a file manager
NSFileManager *fileManager = [NSFileManager defaultManager];
// Does the database already exist? (If not, copy it from our bundle)
if(![fileManager fileExistsAtPath:filePath]) {
// Get the bundle location
NSString *bundleDBPath = [[NSBundle mainBundle] pathForResource:fileName ofType:nil];
// Copy the DB to our document directory.
copySucceeded = [fileManager copyItemAtPath:bundleDBPath
toPath:filePath
error:nil];
if(!copySucceeded) {
NSLog(@"copyFromBundle - Unable to copy \"%@\" to document directory.", fileName);
}
else {
NSLog(@"copyFromBundle - Succesfully copied \"%@\" to document directory.", fileName);
}
}
else {
NSLog(@"copyFromBundle - \"%@\" already exists in document directory - ignoring.", fileName);
}
return copySucceeded;
}
这将检查文档目录中是否存在指定文件,如果该文件尚不存在,则从该包中复制该文件。