fileExistsAtPath: returning NO for files that exist
IosIos Problem Overview
At a point in my code fileExistsAtPath: is returning NO for files that I have confirmed exist. I've been scratching my head at this and can't figure out why its not working, so changed it to this code as this directory absolutely exists but if it doesn't gets created anyway.
NSError* err = nil;
NSURL *dir = [[NSFileManager defaultManager] URLForDirectory:NSApplicationSupportDirectory
inDomain:NSUserDomainMask
appropriateForURL:nil
create: YES
error:&err];
BOOL exists = [[NSFileManager defaultManager] fileExistsAtPath:[dir absoluteString]];
After running this code the application directory folder exists and err is 0, yet exists is NO.
How can this be?
TIA
Ios Solutions
Solution 1 - Ios
You should use [dir path]
, not [dir absoluteString]
.
Solution 2 - Ios
I was bashing my head against the wall for a few hours. Apparently on each and every run in xcode (on simulator) the app directory path was changing. The UUID part of it. So instead of storing the fullpath I ended up persisting the path postfix and prefixing that with whatever storage class is implied: temporary, cached or documents :-[ You realize why you have to sometimes run on device even if you don't explore the depths of Metal, GLES or multitouch? ;^)
Solution 3 - Ios
There is a distinction between path and url. A path in unix representation is the location where your particular file or directory exists. Like "/Users/username/Desktop/myfile.txt"
Wheres a url not only contains the location but scheme as well, e.g: http:// or https:// and in our case a file url (file:///Users/username/Desktop/myfile.txt)
Methods like fileExistsAtPath
or removeItemAtPath
need path in the parameter rather than a url.
While methods like copyItemAtURL:toURL:error:(NSError * _Nullable *)error
expects a url.
Use path
attribute of NSURL
object to retrieve the path. absoluteString
gives you the path along with the scheme.