将文件放置在您的项目文件结构中。
因此它们会被复制到您的 App Bundle 中,并可通过文档目录访问。
要将文件正确添加到您的 iOS 项目:
- 右键单击左侧文件列表顶部的项目图标。
- 选择
Add files to <YourProjectName>
- 选择要包含的文件夹/文件,然后单击添加。
- 不要忘记从给定列表中选择正确的
target。请参考截图。
- 如果您的资源不是单个文件而是目录结构,并且您希望复制所有目录树,请记住选择添加的文件夹:创建组
在 XCode 6.x 中添加弹出窗口的文件如下所示:
构建目标后,打开捆绑包,您的目录结构将完整地存在于其中。不仅如此,这些文件还可以通过 iOS SDK 访问,如下所示。
因此,您可能需要将它们复制到应用内的文档/库目录,因为您可能希望在应用内访问它们。
使用以下代码复制它们。
// Check if the file has already been saved to the users phone, if not then copy it over
BOOL success;
NSString *fileName = @"test.jpg";
NSString *LIBRARY_DIR_PATH = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *filePath = [LIBRARY_DIR_PATH stringByAppendingPathComponent:fileName];
NSLog(@"%@",filePath);
// Create a FileManager object, we will use this to check the status
// of the file and to copy it over if required
NSFileManager *fileManager = [NSFileManager defaultManager];
// Check if the file has already been created in the users filesystem
success = [fileManager fileExistsAtPath:filePath];
// If the file already exists then return without doing anything
if(success) return;
// Else,
NSLog(@"FILE WASN'T THERE! SO GONNA COPY IT!");
// then proceed to copy the file from the application to the users filesystem
// Get the path to the files in the application package
NSString *filePathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:fileName];
// Copy the file from the package to the users filesystem
[fileManager copyItemAtPath:filePathFromApp toPath:filePath error:nil];
希望上面的代码示例对你来说是清楚的。
因此,无论何时您想在您的应用程序中访问该文件,您都可以通过获取该文件的路径来获得对该文件的引用,如下所示:
NSString *sqliteDB = [LIBRARY_DIR_PATH stringByAppendingPathComponent:fileName];
注意:在任何情况下,如果您需要将文件复制到用户应用安装位置内的Documents 目录,请将LIBRARY_DIR_PATH 替换为以下内容:
NSString *DOCUMENTS_DIR_PATH = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
希望这个回答对你有帮助!
干杯!