Check if file exists in URL instead of path

How to check if a file exists in the URL (instead of the path) to set the default pre-populated repository in 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 read that in recent versions of templates, the applicationDocumentsDirectory method returns a URL, so I changed the code to use NSURL objects to represent the file path. But in [fileManager fileExistsAtPath:storePath] I need to change fileExistsAtPath to something like fileExistsAtURL (obviously it does not exist).

I checked the NSFileManager class reference, and I did not find a suitable task suitable for my purpose.

Any clues?

+49
objective-c nsfilemanager
Oct 24 '11 at 16:33
source share
3 answers
 if (![fileManager fileExistsAtPath:[storeURL path]]) ... 

From the documentation :

If this URL contains the file URL (as determined using isFileURL), the return value of this method is suitable for input to the NSFileManager or NSPathUtilities methods. If the path has a trailing slash, loses.

+97
Oct 24 '11 at 18:38
source share

For the URL file system, NSURL itself has a method for checking URL availability

 NSError *error; NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"Food.sqlite"]; if ([storeURL checkResourceIsReachableAndReturnError:&error]) { // do something } else { NSLog(@"%@", error); } 
+11
Dec 31 '15 at 9:03
source share
 if (![fileManager fileExistsAtPath:[storeURL path]]) 

ok but be careful: for a url like:

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

[storeURL path] will give you this path (applicable to [storeURL lastPathComponent] :

 ..../Documents/1158a3c96ca22c41b8e731b1d1af0e1e 

but if you use lastPathComponent for 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, because in the URL '?' used for GET parameters, but if you mix with a string, you may have problems.

+4
Sep 03
source share



All Articles