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);
});
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.