Tuesday, October 4, 2011

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;

34 comments:

  1. 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;

    ReplyDelete
  2. 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"
    ...

    ReplyDelete
  3. How to import Foundation/Foundation.h?

    ReplyDelete
  4. Definitely believe that that you said. Your favourite reason appeared to be on the web the easiest factor to take note of. I say to you, I certainly get irked at the same time as other folks consider concerns that they plainly don't understand about. You controlled to hit the nail upon the top as smartly as outlined out the whole thing with no need side effect , other people can take a signal. Will probably be again to get more. Thanks

    ReplyDelete
  5. Hi there, just became aware of your blog through Google,
    and found that it's really informative. I'm
    going to watch out for brussels. I'll be grateful if you continue this in future. Lots of people will be benefited from your writing. Cheers!

    ReplyDelete
  6. Nearly all of whatever you say is astonishingly accurate and that makes me wonder the reason why I had not looked at this with this light before. This particular article truly did turn the light on for me personally as far as this issue goes. However at this time there is actually 1 point I am not necessarily too cozy with and while I attempt to reconcile that with the main idea of the position, allow me observe exactly what the rest of your subscribers have to say.Well done.

    ReplyDelete
  7. 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;

    ReplyDelete
  8. 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;

    ReplyDelete
  9. I used to be suggested this blog by means of my cousin. I am not positive whether this submit is written by way of him as nobody else understand such special about my trouble. You're amazing! Thanks!

    ReplyDelete
  10. Magnificent post, very informative. I'm wondering why the opposite experts of this sector do not realize this. You should proceed your writing. I am confident, you have a huge readers' base already!|What's Happening i'm new to this, I stumbled upon this I've found It positively helpful and it has aided me out loads. I hope to contribute & help different users like its aided me. Good job.

    ReplyDelete
  11. Anyone fundamentally help to make tremendously content I might declare. That is the brand new My partner and i visited your site webpage and so significantly? We surprised while using evaluation you've made to generate this particular offered incredible. Good approach!

    ReplyDelete
  12. If you ever require a guardian for your estate the process can be expensive so declare your guardian ahead of time.

    ReplyDelete
  13. Superb things entirely, you only obtained your logo new reader. . kiss destroyer cover juniors v neck t-shirtPrecisely what will you recommend in terms of ones offered that you simply developed a few days prior to now? Every positive?

    ReplyDelete
  14. Very nice post. I just stumbled upon your weblog and wished to mention that I have truly enjoyed surfing around your weblog posts. In any case I will be subscribing to your feed and I hope you write again soon!

    ReplyDelete
  15. How to become a tutor in creative writing for Further education and or teach English as a second language?

    ReplyDelete
  16. Pretty nice post. I just stumbled upon your blog and wanted to say that I've really enjoyed browsing your blog posts.
    After all I will be subscribing to your feed and I hope you write again very soon!

    My webpage - Ninja Heroes hack apk

    ReplyDelete
  17. I do not even know how I ended up here, however I thought this post
    was good. I don't recognize who you're however certainly you're going
    to a famous blogger when you are not already. Cheers!

    Feel free to visit my web site: racing rivals cheats

    ReplyDelete
  18. Do you have a spam issue on this blog; I also am a blogger,
    and I was wanting to know your situation; many of us have developed some nice procedures and we are looking to exchange methods with others, why not shoot me an email if interested.

    ReplyDelete
  19. I am reading your website and an excellent method to promote your content
    came to my mind. Search in google for: Willard's Tips - SM Traffic

    ReplyDelete
  20. I know this if off topic but I'm looking into starting my own blog and was curious what all is
    required to get setup? I'm assuming having a blog like yours would cost a pretty penny?
    I'm not very internet savvy so I'm not 100% certain. Any tips or advice would be greatly appreciated.
    Cheers

    Also visit my webpage Diamond Digger Saga Hack

    ReplyDelete
  21. best website directory...

    "[...]The Hacker’s Corner » Blog Archive » Reading and writing files from an iOS FireMonkey application[...]"...

    ReplyDelete
  22. I am extremely imressed with your writing skills as well as with thee layout on your blog.
    Is this a paid theme or did you moddify it yourself?
    Either way keep up the excellent quality writing, it's rare to see a greatt blog like this one nowadays.


    Feel free to visit my blog post ... marketing

    ReplyDelete
  23. Hello, for all time i used to check web site posts here in the early hours in the break of day,
    since i love to find out more and more.

    ReplyDelete
  24. For most up-to-date information you have to visit the
    web and on the web I found this web page as a most excellent website for latest updates.


    my web page - Animas Online Hack - Nona,

    ReplyDelete
  25. Admiring the time and effort you put into your blog and in depth information you offer.
    It's good to come across a blog every once in a while that isn't the same old rehashed information. Fantastic read!
    I've bookmarked your site and I'm including your RSS feeds to my Google account.


    Feel free to surf to my site Dragons Rise of Berk Hack (Ruthie)

    ReplyDelete
  26. Hello, I believe your site might be having browser compatibility issues.
    Whenever I take a look at your blog in Safari, it looks fine
    however, when opening in Internet Explorer, it's got some overlapping issues.
    I simply wanted to give you a quick heads up! Besides that, wonderful blog!

    ReplyDelete
  27. Binary Increase will soon join the top-tier of flagship binary choices robots, together with my
    Top 5 record beneath, A.I. App and Skilled Robot.

    ReplyDelete
  28. Excellent blog here! Also your site loads up fast! What host are
    you using? Can I am getting your affiliate link to your host?
    I want my web site loaded up as quickly as yours
    lol

    Look at my web site :: http://naturalclearvisionreviewx.blogspot.com/

    ReplyDelete
  29. I think that is among the such a lot significant
    information for me. And i'm glad reading your article.
    However wanna observation on few common issues, The site taste is great, the articles is in reality excellent : D.
    Good process, cheers

    Feel free to visit my web page ... natural clear vision download

    ReplyDelete
  30. magnificent publish, very informative. I wonder why the
    other specialists of this sector do not notice this. You should proceed your writing.
    I am sure, you've a huge readers' base already!

    ReplyDelete
  31. Being motivated was a big hurdle but one of tthe most important factors in losng weight.
    If you stick with it yoou can realize a healthier lifestyle and improved
    body image. Annd visit my website to learn more information about weight loss.

    ReplyDelete
  32. I enjoy what you guys tend to be up too. This sort of clever work and exposure!
    Keep up the amazing works guys I've incorporated you guys to my personal blogroll.


    Also visit my blog battle glory 2 hack Iphone

    ReplyDelete
  33. We're a bunch of volunteers and opening a brand new scheme in our community.

    Your site offered us with helpful information to work on. You've done an impressive process and our entire
    neighborhood will be thankful to you.

    ReplyDelete

Note: Only a member of this blog may post a comment.