简体   繁体   中英

Opening file in iPhone application - NSFileManager isReadableFileAtPath returning NO

Here is my code:

-(BOOL)application:(UIApplication *)application
           openURL:(NSURL *)url
 sourceApplication:(NSString *)sourceApplication
        annotation:(id)annotation {

    if (url != nil && [url isFileURL]) {
        NSString* documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];

        if ( [[NSFileManager defaultManager] isReadableFileAtPath:[url absoluteString]] ) {
            NSLog(@"READABLE!");
            [[NSFileManager defaultManager] copyItemAtPath:[url absoluteString] toPath:[documentsPath stringByAppendingString:@"/timecode.xml"] error:nil];
        } else {
            NSLog(@"NOT READABLE!");
        }

        BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:[documentsPath stringByAppendingString:@"/timecode.xml"]];

        if (fileExists) {
            NSLog(@"THERE!");
        } else {
            NSLog(@"NOT THERE!");
        }
    }
}

For some reason when I open a file from the mail app (or any other app, including good reader) into my app, it says it isn't readable. And obviously, the file doesn't exist.

Any ideas why this is happening?

Because an URL is not a path.

[url absoluteString]

looks like

file:///var/mobile/XXXXXXXX/MyApp.app/Documents/foo.txt

You need to use

[url path]

instead.

Also, two comments:

url != nil && [url isFileURL]

is highly superfluous.

[url isFileURL]

will return NO anyway if the URL is nil (since messaging nil always returns zero).

Two:

[documentsPath stringByAppendingString:@"/timecode.xml"]

Don't reinvent the wheel/try to guess the path separator. This line should be

[documentsPath stringByAppendingPathComponent:@"timecode.xml"]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM