You can save the text to your app's Documents directory and allow them to export it through iTunes. You can also allow them to email it.
Saving it to disk:
To save in the App's documents directory, you'll need to do a few things. First of all, you'll need to get the URL to the path directory. A method for this is conveniently generated by Xcode when you make a Core Data based project. Here's that method:
- (NSURL *)applicationDocumentsDirectory{
return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}
Next, you'll want to take that that URL and use it to write our to your App's documents directory. In the simples case, we have a string, called someText
, which we'll be writing out to the Documents directory. Here's what that looks like:
NSString *someText = "Here's to some awesome text.";
We have a path, called path
. Note that we take the path to the documents directory and then append a filename. You could replace someText.txt
with whatever filename you want to use.
NSString *path = [NSString stringWithFormat:@"%@",[[[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"someText.txt"] absoluteString]];
We tell the the string to write itself out to the file (in this case atomically) and if it fails, we populate the error
object, which we can read out later if necessary. Note the option for "atomically" here. If it's set to YES
, the app will write the text into a buffer and rename it afterward. If it's not set to YES
, the text will be written straight to text. This makes a difference in multithreaded environments and can protect your text from being some mangled result, but atomic writing is slower.
Here's all of the above code at once:
//Write to the file
[someText writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:&error];
NSString *someText = "Here's to some awesome text.";
NSError *error = nil;
NSString *path = [NSString stringWithFormat:@"%@",[[[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"someText.txt"] absoluteString]];
//Write to the file
[someText writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:&error];
Reading the file from iTunes:
This is the fun part. In Xcode, you need to add a key to your app's Info.plist file. Here's what that is going to look like in Xcode 4:
Now, in iTunes, your App's documents directory will be visible.
Alternatively (or in addition to iTunes), you could use the MessageUI framework and allow the user to email the file.