I am trying to write a list to a text file that is included in my project (Deck.txt) the relevant code is as follows:
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"Deck" ofType:@"txt"];
NSFileHandle *fileHandle = [NSFileHandle fileHandleForWritingAtPath:filePath];
deck = [[NSString alloc]initWithFormat: @"%@\n%@ %@",file, txtQuantity.text, cardName];
//[deck writeToFile:filePath atomically:YES encoding:NSStringEncodingConversionAllowLossy error:nil];
[fileHandle writeData:[deck dataUsingEncoding:NSUTF8StringEncoding]];
[fileHandle closeFile];
When I run the code it will not save to the text document however, or at least not the one included in my project. It will still create the list and read from the file all the data that I am trying to write, but when I close the program no changes are made to the text document. Any help would be most appreciated.
Create a text fileOpen the Documents app. Go to the folder where you want a new text file to be saved. Tap the Plus button at the bottom right. Tap Text File.
To add a text file to the project, right-click on the project folder in the project view in the left pane and select the option New Item... In the dialog that appears, select the Other category and the Empty file option. Name the file numbers. txt.
To create a text file in Swift, call createFile() function on the file manager object, and pass the file path and contents to the function.
To read a Text File in Swift, we can prepare the file url and then use String initializer init(contentsOf: url) that returns file content as a string.
If you've already got your NSData instance, you can certainly just write the data to the built in document directory on the device. With a bit of searching, it's not hard to find the location when run from the simulator for checking purposes.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDir = [paths objectAtIndex: 0];
NSString *docFile = [docDir stringByAppendingPathComponent: @"deck.txt"];
//your variable "deck"
[deck writeToFile: docFile atomically: NO];
This will certainly write to a file in your documents directory. It should only be a matter of altering your code to read from the directory.
setup your filepath with this (as an example):
NSString *filePath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/dt"];
then store the data like this:
[VARNAME writeToFile:filePath atomically:YES (or NO)];
I think what you are trying to do can be done more simply like this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With