Friday, December 28, 2012

iOS: Appending to an existing text file

I wanted to make an update to one of my iOS Apps.
iOS Book Organizer

Many users have asked me the ability to export all the saved book data in the app. I started researching into how to write data to a text file and then email the file.

I found that it is not that straightforward to append to a text file on iOS. Most examples I read told me to write the data in one swoop.  

I am hesitant in reading all the data to memory and then attempt to write the data in one big swoop. After due research, I think, I have an answer to this problem.

....
>> read data from your sqllite database or from the ui.
>> if there is multiple records in your database, loop through the data.

>> Before you loop through, create the file

//get the documents path
NSArray *documentsPath = NSSearchPathForDirectoriesInDomain(NSDocumentDirectory, NSUserDomainMask,YES);

//your document folder is the first one in the array list
NSString *yourDirectory = [documentsPath objectAtIndex:0];

//create your file here.
NSString *yourfile = [yourDirectory stringByAppendingPathComponent:@"booklist.txt"];

//create a file handle
NSFileHandle *yourHandle = [NSFileHandle fileHandleForUpdatingAtPath:yourFile];


//loop through ur data
//for every iteration

[yourHandle seekToEndOfFile];
[yourHandle writeData:[yourString dataUsinigEncoding:NSUTF8StringEncoding];

//keep writing.
//after all the data is written.

[yourHandle closeFile];

Your text file is now created with your data.

Next post: How to read from this file and attach it to an email.


No comments: