IOS app - Bundle with text file

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

And how can I reference the file at runtime?

+4
source share
2 answers

If your file will always be read-only (updated only as part of the application update), add it to your application resources in your project. Then you just read the file from the application package:

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

If you need to provide the source file with your application, but make updates at runtime, you need to pack the file as described above, but when you first launch the application, you need to copy the file to another writable location in your sandbox app.

 // 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]; 
+5
source

Good explanation here http://www.cocoawithlove.com/2010/05/finding-or-creating-application-support.html

The directory must be created at runtime and the files moved from the main package, then you can access them using the methods described in the link.

0
source

Source: https://habr.com/ru/post/1447068/


All Articles