Saturday, September 25, 2010

Unable to write to filesystem using Titanium

This took several hours to figure out...

In Titanium Mobile it allows you to create and write to files in the Resources directory (Titanium.Filesystem.resourcesDirectory) using the emulator, but it fails when you try to run it on the iPhone. This is because you don't have actual write permissions on that directory -- you need to save data to the Titanium.Filesystem.applicationDataDirectory.

Here is how you write to a file: (btw -- if the file does not already exist, it creates it automatically -- you don't need to use the Ti.Filesystem.createFile() method)

var f = Titanium.Filesystem.getFile(Titanium.Filesystem.applicationDataDirectory, 'myFile.txt');
f.write('this is the new file');

To read the contents of a file:

var g = Titanium.Filesystem.getFile(Titanium.Filesystem.applicationDataDirectory, 'myFile.txt');
var contents = g.open();
Titanium.API.info("Contents of the file = " + contents.text);

No comments: