Domanda

When the App Delegate method for handling an opened file (from another app) gets called in my app, the URL it passes to my app is nil... or at least that's what NSFileManager tells me, because the file does really exist in the location it specifies.

Why is NSFileManager telling me that a file URL to a file in my app's document inbox does not exist? Here's how I'm handling the URL:

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
    if (![[NSFileManager defaultManager] fileExistsAtPath:[url absoluteString]]) {
        NSLog(@"File does not exist at path: %@", [url absoluteString]);
    } else {
        ...
    }
}

I've been trying to figure this out for a while, but I can't think of any reason as to why the url parameter here would be registering as nonexistent. It's probably something really simple. Maybe the absoluteString thing is tripping up NSFileManager?

Any ideas? I've searched and searched, but found nothing - and can think of nothing.

È stato utile?

Soluzione

The correct method to convert a (file) URL to a path is path, not absoluteString :

if (![[NSFileManager defaultManager] fileExistsAtPath:[url path]]) {
   ...

From the documentation of -[NSURL path]:

If this URL object contains a file URL (as determined with isFileURL), the return value of this method is suitable for input into methods of NSFileManager or NSPathUtilities.

absoluteString, on the other hand, returns a URL string like "file:///path/to/file".

Altri suggerimenti

The first mistake here is you are using -[NSURL absoluteString]. You want path instead.

However, another problem is likely even testing for the existence of the file. This is rarely useful, and you should just attempt to perform some operation on the file anyway, handling any failures that occur.

If you really do have to test for its existence, use the more modern -[NSURL checkResourceIsReachableAndReturnError:] instead.

You should check the url before use NSFileManager:

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
    if (url && [url isFileURL])
    {
        if (![[NSFileManager defaultManager] fileExistsAtPath:[url absoluteString]]) {
        NSLog(@"File does not exist at path: %@", [url absoluteString]);
        } 
        else 
        {
           ...
        }
    }
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top