Check if file exists at URL instead of path

荒凉一梦 提交于 2019-12-06 16:29:32

问题


How can I check if a file exists at a URL (instead of a path), in order to set a pre-populated default store into the iPhone Simulator:

NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"Food.sqlite"];
/*
 Set up the store.
 For the sake of illustration, provide a pre-populated default store.
 */
NSFileManager *fileManager = [NSFileManager defaultManager];
// If the expected store doesn't exist, copy the default store.
if (![fileManager fileExistsAtPath:storePath]) {
    NSString *defaultStorePath = [[NSBundle mainBundle] pathForResource:@"Food" ofType:@"sqlite"];
    if (defaultStorePath) {
        [fileManager copyItemAtPath:defaultStorePath toPath:storePath error:NULL];
    }
}

I've read that in recent versions of the templates, the applicationDocumentsDirectory method returns an URL, so I've changed the code to use NSURL objects to represent the file path. But at [fileManager fileExistsAtPath:storePath], I need to change fileExistsAtPath to something like fileExistsAtURL (obviously it doesn't exist).

I've checked the NSFileManager Class Reference and I didn't find any suitable task suited for my purpose.

Any hints please?


回答1:


if (![fileManager fileExistsAtPath:[storeURL path]]) 
...

From the documentation:

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. If the path has a trailing slash it is stripped.




回答2:


For a file system URL NSURL itself has a method to check the reachability of an URL

NSError *error;
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"Food.sqlite"];
if ([storeURL checkResourceIsReachableAndReturnError:&error]) {
  // do something
} else {
  NSLog(@"%@", error);
}



回答3:


if (![fileManager fileExistsAtPath:[storeURL path]]) 

is ok, but be carful : for an url like :

..../Documents/1158a3c96ca22c41b8e731b1d1af0e1e?d=mm&s=50

[storeURL path] will give you that path (it apply to [storeURL lastPathComponent] :

..../Documents/1158a3c96ca22c41b8e731b1d1af0e1e

but if you use lastPathComponent on a string like /var/mobile/Applications/DB92F4DC-49E4-4B4A-8271-6A9DAE6963BC/Documents/1158a3c96ca22c41b8e731b1d1af0e1e?d=mm&s=50, it will give you 1158a3c96ca22c41b8e731b1d1af0e1e?d=mm&s=50

And that's good, since in a url, '?' is used for GET parameters, but if you mix with string, you might have troubles.



来源:https://stackoverflow.com/questions/7878828/check-if-file-exists-at-url-instead-of-path

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!