Sunday, April 22, 2012

How to check if a file exists in Documents folder?


I have an application with In-App Purchase, that when the user buy something, download one html file into the Documents folder of my app.



Now I must check if this HTML file exists, so if true, load this HTML file, else load my default html page.



How I can do that? With NSFileManager i can't get outside of mainBundle..



Thanks to everyone can help me!


Source: Tips4all

2 comments:

  1. NSString* documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];


    ... gives you the path to the documents directory. The following checks if there's a file named foo.html:

    NSString* foofile = [documentsPath stringByAppendingPathComponent:@"foo.html"];
    BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:foofile];

    ReplyDelete
  2. If you set up your file system differently or looking for a different way of setting up a file system and then checking if a file exists in the documents folder heres an another example. also show dynamic checking

    for (int i = 0; i < numberHere; ++i){
    NSFileManager* fileMgr = [NSFileManager defaultManager];
    NSString *documentsDirectory = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
    NSString* imageName = [NSString stringWithFormat:@"image-%@.png", i];
    NSString* currentFile = [documentsDirectory stringByAppendingPathComponent:imageName];
    BOOL fileExists = [fileMgr fileExistsAtPath:currentFile];
    if (fileExists == NO){
    cout << "DOESNT Exist!" << endl;
    } else {
    cout << "DOES Exist!" << endl;
    }
    }

    ReplyDelete