Preloading Documents into iOS App

2019-02-11 05:19发布

问题:

The Situation: I have an iOS app that deals with files and lets the user save, edit, open and perform various operations with these files. I'd like to be able to have some pre-made documents for the user to look at when they open the app (ex. a template) alongside their own custom documents.

The Problem: How can I create a document (or template file) and have it appear in the Documents folder after the user installs my app and launches it (and all preceding times)?

Background: This document (the one that'd be installed into the app's documents directory) is created by me, not the user.

I know that to do this you need to save it in your bundle, and then when your app runs for the first time silently copy it into the Documents Directory. Should I copy it in the appDidFinishLaunchingWithOptions method or in my viewDidLoad method and write logic to detect if it's the first time the app has run?

My Code: At this webpage: http://textsnip.com/d35fbc     But when it runs, it always says: "File does not exist [in documents folder]", then it tells me that it's being copied. The problem is that when I examine the app's documents folder it is never there, it's still in the bundle.

Why won't it copy with this code How does this work?

回答1:

the files must in fact be added to the app bundle, then copied silently when the app launches.

The following code copies a text file from the top level of my bundle to the documents directory if it doesn't already exist.

NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];

NSString *txtPath = [documentsDirectory stringByAppendingPathComponent:@"txtFile.txt"];

if ([fileManager fileExistsAtPath:txtPath] == NO) {
    NSString *resourcePath = [[NSBundle mainBundle] pathForResource:@"txtFile" ofType:@"txt"];
    [fileManager copyItemAtPath:resourcePath toPath:txtPath error:&error];
}

The only flaw in this code is that if the user deletes the file, it immediately reappears when they open the app again.



回答2:

As you said, you include it in your app bundle (add it to your project and make sure it's part of your target). Then you can access it's path by calling something like this:

NSString *bundlePath = [[NSBundle mainBundle] pathForResource:@"MyTemplateDoc" 
                                                       ofType:@"extension"];

Then you copy it to your app's documents folder.

NSString *docPath = <a path in your documents folder>
NSError *error = nil;
[[NSFileManager defaultManager] copyItemAtPath:bundlePath 
                                        toPath:docPath 
                                         error:&error];
if (error) {
    // handle copy error.
}