iOS - 捆绑应用程序与文本文件 [英] iOS - Bundle app with text file

查看:95
本文介绍了iOS - 捆绑应用程序与文本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个.json文件,我想与我的应用程序捆绑为一个资源。我已阅读文件系统编程指南,它表示您应该将支持文件放在< Application_Home> / Library / Application Support 中。那么如何在构建我的应用程序之前将我的.json文件放在这个目录中?

I have a .json file that I want to be bundled with my application as a resource. I've read the File System Programming Guide which says that you should put support files in the <Application_Home>/Library/Application Support. So how do I put my .json file in this directory before building my application?

如何在运行时引用该文件?

And how would I reference the file during runtime?

推荐答案

如果您的文件将始终是只读的(仅作为应用更新的一部分进行更新),请将该文件添加到您项目中的应用资源。然后你只需从应用程序包中读取文件:

If your file will always be read-only (only updated as part of an app update), then add the file to your app's resources in your project. Then you simply read the file from the app's bundle:

// assume a filename of file.txt. Update as needed
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"file" ofType:@"txt"];

如果您需要为应用程序提供初始文件,但在运行时进行更新,上述文件,但第一次运行应用程序时,您需要将该文件复制到应用程序沙盒中的另一个可写位置。

If you need to provide an initial file with your app but make updates during runtime then you need to package the file like above, but the first time your app is run you need to copy the file to another, writable location in your app's sandbox.

// Get the Application Support directory
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES);
NSString *appSupportDirectory = [paths objectAtIndex:0];

// Create this path in the app sandbox (it doesn't exist by default)
NSFileManager *fileManager = [NSFileManager defaultManager];
[fileManager createDirectoryAtPath:appSupportDirectory withIntermediateDirectories:YES attributes:nil error:nil];

// Copy the file from the app bundle to the application support directory
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"file" ofType:@"txt"];
NSString *newPath = [appSupportDirectory stringByAppendingPathComponent:[filePath lastPathComponent]];
[fileManager copyItemAtPath:filePath toPath:newPath error:nil];

这篇关于iOS - 捆绑应用程序与文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆