Reading and writing files from an iOS FireMonkey application

Here’s an example of how you can read and write files in your iOS FireMonkey application.

Enjoy!

{$IFDEF FPC}
var
content : NSString;
{$ENDIF}

{$IFDEF FPC}
function MyFileName : NSString;
var
paths : NSArray;
fileName : NSString;
begin
paths := NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, True);
fileName := paths.objectAtIndex(0);
fileName.stringByAppendingString(NSSTR(PChar(’/myfile.txt’)));
Result := fileName;
end;
{$ENDIF}

procedure TForm1.Button1Click(Sender: TObject);
begin
// Write to file
{$IFDEF FPC}
Label2.Text := ‘Wrote to: ‘+String(MyFileName.UTF8String);
content := NSSTR(PChar(String(Memo1.Text)));
content.writeToFile_atomically_encoding_error(MyFileName,False,NSStringEncodingConversionAllowLossy,nil);
content.release;
{$ENDIF}
end;

procedure TForm1.Button2Click(Sender: TObject);
begin
// Read from file
{$IFDEF FPC}
Label2.Text := ‘Read from ‘+String(MyFileName.UTF8String);
content.InitWithContentsOfFile_usedEncoding_error(MyFileName,nil,nil);
Memo1.Text := String(content.UTF8String);
content.release;
{$ENDIF}
end;

7 Responses to “Reading and writing files from an iOS FireMonkey application”

  1. Anders Ohlsson Says:

    Even simpler way of getting the filename:

    function MyFileName : NSString;
    var
    fileName : NSString;
    begin
    fileName := NSSTR(PChar(ExtractFilePath(ParamStr(0))+’myfile.txt’));
    Result := fileName;
    end;

  2. Andre Miertschink Says:

    Hi Anders,

    I’m not sure that
    fileName := NSSTR(PChar(ExtractFilePath(ParamStr(0))+’myfile.txt’));
    is correct, have you tried? For me it worked to read and store on iPhone simulator, but not on iPhone itself. The function ExtractFilePath(ParamStr(0)) returns a directory "/AppName.app/", but this is not a correct location to store files. Check:

    http://developer.apple.com/library/ios/#documentation/iphone/conceptual/iphoneosprogrammingguide/RuntimeEnvironment/RuntimeEnvironment.html

    You need to remove the final part from the directory ("AppName.app/") and later add the correct directory for it (e.g. /Library/Preferences).

    For example I stored successfully text files at: "/Documents"

    And you don’t need to use FPC functions. For example I was able to read and store files using all functions available from Delphi XE2. For example::

    procedure TForm1.FormCreate(Sender: TObject);
    var
    strTmp: string;
    {$IFDEF IOS}
    begin
    strTmp := ExtractFilePath(paramstr(0));
    strTmp := Copy(strTmp, 1, length(strTmp) - 13); //Just for TEST. Remove
    from end: Project1.app/
    DocumentDir := strTmp + ‘Documents/’;
    TempFileName := DocumentDirDelphi + ‘Text.txt’;
    Label1.text := DocumentDirDelphi;
    end;

    procedure TForm1.btnWriteClick(Sender: TObject); var
    textFileTmp: TextFile;
    strTmp: string;
    error: boolean;
    begin
    error := false;
    // Try to open the file for writing and write some lines
    AssignFile(textFileTmp, TempFileName);
    try
    ReWrite(textFileTmp);
    except
    //Require changes to improve the exception handling
    error := True;
    end;
    if error then
    exit;
    Writeln(textFileTmp, ‘Hello ADUG’);
    Writeln(textFileTmp, ‘Second Line’);
    CloseFile(textFileTmp);
    end;

    procedure TForm1.btnReadClick(Sender: TObject); var
    textFileTmp: TextFile;
    strTmp: string;
    begin
    // Reopen the file for reading only and display content
    if fileExists(TempFileName) then
    begin
    AssignFile(textFileTmp, TempFileName);
    Reset(textFileTmp);
    while not Eof(textFileTmp) do
    begin
    ReadLn(textFileTmp, strTmp);
    ShowMessage(strTmp);
    end;
    CloseFile(textFileTmp);
    end;
    end;

  3. Andre Miertschink Says:

    Sorry, but the some part of the text was cut.

    Correct:

    You need to remove the final part from the directory ("[ApplicationHome]/AppName.app/") and later add the correct directory for it (e.g. [ApplicationHome]/Library/Preferences).

    For example I stored successfully text files at: "[ApplicationHome]/Documents"

  4. how Says:

    How to import ?

  5. how Says:

    How to import Foundation/Foundation.h?

  6. Phil Francis Says:

    I Have tried this last example using an iPad iOS 6.1 connected to a Mac running OSX Mountain Lion. I have used the code provided by Andre Miertschink above. I am running from XE4 iOS6.1 Debug in project options. When I run and click the Write file button, I get an exception when it tries to write the file. Is there something I am doing wrong ? Thanks

    procedure TfrmMain.btnWriteFileClick(Sender: TObject);
    var textFileTmp: TextFile;
    strTmp: string;
    error: boolean;
    begin

    error := false;
    // Try to open the file for writing and write some lines
    AssignFile(textFileTmp, TempFileName);

    try
    ReWrite(textFileTmp);
    except
    //Require changes to improve the exception handling
    error := True;
    end;

    if error then
    exit;
    Writeln(textFileTmp, ‘Hello ADUG’);
    Writeln(textFileTmp, ‘A Second Line’);
    CloseFile(textFileTmp);

    end;

  7. Phil Francis Says:

    procedure TfrmMain.FormCreate(Sender: TObject);
    var strTmp: string;
    DocumentDirDelphi: String;
    begin
    strTmp := ExtractFilePath(paramstr(0));
    strTmp := Copy(strTmp, 1, length(strTmp) - 13); //Just for TEST. Remove from end: Project1.app/
    DocumentDirDelphi := strTmp + ‘/Documents/’;
    TempFileName := DocumentDirDelphi + ‘Text.txt/’;
    lblMyLabel.text := DocumentDirDelphi;

    end;

Leave a Reply


Bad Behavior has blocked 512 access attempts in the last 7 days.

Close