Saving data using the RAW file
In the previous section, you learned about the Document
directories. Now, in this section we will explore this in more detail. You will learn about saving RAW files in our application's document directory.
Getting ready
We will use the preceding project for this section as well. So, open the project and follow the next section.
How to do it...
Perform the following steps to write data into your Documents
directory:
- Now, we will create a
.txt
file in our folder (which we created in the document directory). Customize the code inviewDidLoad:
as follows:dataPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject] stringByAppendingPathComponent:@"myfile.txt"]; NSLog(@"%@", dataPath);
The preceding code will create a
.txt
file of namemyfile.txt
. - To write something into the file, add the following code:
NSError *error; NSString *stringToWrite = @"1\n2\n3\n4"; dataPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject] stringByAppendingPathComponent:@"myfile.txt"]; [stringToWrite writeToFile:dataPath atomically:YES encoding:NSUTF8StringEncoding error:&error];
The
writeToFile
method is used to write data in our file. - Now, to read the data from the file, there's the
stringWithContentsOfFile
method. So add the following method inside the code:NSString *str = [NSString stringWithContentsOfFile:dataPath encoding:NSUTF8StringEncoding error:&error]; NSLog(@"%@", str);
- To see the
mayflies.txt
file in theDocuments
directory, go to theGoToFolder
finder and pastedataPath
from the console. It will take you tomayflies.txt
. The final file should look something like the following screenshot: - In the screenshot, you can see the two files have been created. As per our code, we have created
myfile.txt
andmyfile.pdf
. We have also createdMyFolder
in the sameDocuments
folder of the app.