微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

iOS – 使用文本文件捆绑应用程序

我有一个.json文件,我希望将其作为资源与我的应用程序捆绑在一起.我已经阅读了 File System Programming Guide,其中说您应该将支持文件放在< Application_Home> / Library / Application Support中.那么在构建我的应用程序之前如何将我的.json文件在这个目录中呢?

如何在运行时引用该文件

解决方法

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

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

如果您需要在应用程序中提供初始文件但在运行时进行更新,则需要像上面那样打包文件,但是第一次运行应用程序时,您需要将文件复制到应用程序沙箱中的另一个可写位置.

// 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];

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐