Titanium Community Questions & Answer Archive

We felt that 6+ years of knowledge should not die so this is the Titanium Community Questions & Answer Archive

Can't save data in a text file with actual iPhone

I am trying to save a string to a text file using the fileSystem. When I run it in the iPhone Simulator, it works perfectly. When I run it in my iPhone 4 (with iOS 4.0) I get the error handler when it doesn't save. I am able to read from the text file in both, the Simulator and the actual iPhone 4, but I can only write in the simulator. Here is the code I am using…

function fn_save_file(data)
{
if(data)
{
var file = Titanium.Filesystem.getFile('number.txt');
if(file.write(data))
{
tabGroup.tabs[0].active = true;
}

    if(!file.write(data)) // tell user if save is unsuccessful
    {
        var save_error = Ti.UI.createAlertDialog({
            title: 'SAVE ERROR',
            message: 'Could not save file',
            buttonNames: ['OK']
        });
        save_error.show();
        tabGroup.tabs[0].active = true;
    }
}

}

setNumber.addEventListener('click', function(e)
{
fn_save_file(txt1.value);
});

— asked December 6th 2010 by Norman Ortiz
  • data
  • filesystem
  • save
  • text
  • txt
  • write
0 Comments

1 Answer

  • Accepted Answer

    Norman,

    The problem is you are not providing a path to the file, so it is defaulting to the Resources folder. On the device, this folder is read-only so any attempt to use the .write() method will fail.

    You need to use a writeable folder, e.g.:

    var file = Ti.Filesystem.getFile( Ti.Filesystem.applicationDataDirectory + '\number.txt');

    You may also want to look at how the Kitchen Sink does filesystem operations, for more examples.

    — answered December 6th 2010 by Doug Handy
    permalink
    0 Comments
The ownership of individual contributions to this community generated content is retained by the authors of their contributions.
All trademarks remain the property of the respective owner.