Search code examples
iosiphonexcodewebviewnsfilemanager

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


Solution

  • Swift 3:

    let documentsURL = try! FileManager().url(for: .documentDirectory,
                                              in: .userDomainMask,
                                              appropriateFor: nil,
                                              create: true)
    

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

    let fooURL = documentsURL.appendingPathComponent("foo.html")
    let fileExists = FileManager().fileExists(atPath: fooURL.path)
    

    Objective-C:

    NSString* documentsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
    
    NSString* foofile = [documentsPath stringByAppendingPathComponent:@"foo.html"];
    BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:foofile];