Document Or cache Path Changes on every launch in iOS 8 - ios

As i am downloading a video in my app and keeping it in local cache/Document path and showing when necessary. It is working in iOS 7 but the avplayer not showing video in iOS 8 and above. As i have read that the document/cache path is changed on every launch in iOS 8. The issue is, I have to download video once and show it multiple times in my app. So how can i reach the same path again and again to show video in app.
Here is my code:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
// NSLog(#"Document folder: %#", paths);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSLog(#"Document folder: %#", documentsDirectory);
In The log I am getting different path on each launch. Any Help would be appreciated. Thanks

I got the answer. As the absolute path is changing on every launch, we can save the data on relative path and retrieve it on appending absolute path and relative path.
This is how we can save the data on the relative path:
NSString *documentsDirectory = #"MyFolder";
documentsDirectory = [documentsDirectory stringByAppendingPathComponent:filename];
NSString *relativePath = documentsDirectory;
But when you read the file you have to use absolute path + relative path:
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *fullCachePath = ((NSURL*)[[fileManager URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject] ).path;
NSString *fullPath = [fullCachePath stringByAppendingPathComponent:relativePath];
For Database also store data on the relative path only. But while reading take the absolute path and append the relative path coming from database and read.
Its Working here.

The path to the application container or sandbox changing should be an expected condition. You should not store the absolute filesystem path to a sandbox directory; instead store the path relative to that directory, and append that to the result of NSSearchPathForDirectoriesInDomains each time.

It is recommended to use bookmarks to reference file system resources.
If you want to save the location of a file persistently, use the bookmark capabilities of NSURL. A bookmark is an opaque data structure, enclosed in an NSData object, that describes the location of a file. Whereas path- and file reference URLs are potentially fragile between launches of your app, a bookmark can usually be used to re-create a URL to a file even in cases where the file was moved or renamed.
A bookmark provides a persistent reference to a file-system resource. When you resolve a bookmark, you obtain a URL to the resource’s current location. A bookmark’s association with a file-system resource (typically a file or folder) usually continues to work if the user moves or renames the resource, or if the user relaunches your app or restarts the system.
For a sample code, checkout the File System Programming Guide -> Locating Files Using Bookmarks
If you want use URL directly for backward compatibility, I have a fix code:
#interface NSURL (App)
/**
This method try to rebuild a file url relative to application’s home directory.
If the reciver is not a file url or not in the home directory. The original URL returns.
#code
NSString *homePath = NSHomeDirectory();
// Assume "/Something/Application/B383551F-41C1-4E3D-8EA9-8D76E4AFA919"
NSURL *test;
test = [NSURL fileURLWithPath:homePath];
[test URLByResolvingApplicationDirectoryChange];
// file://Something/Application/B383551F-41C1-4E3D-8EA9-8D76E4AFA919
test = [NSURL URLWithString:#"file:///Foo/bar"];
[test URLByResolvingApplicationDirectoryChange];
// file:///Foo/bar
test = [NSURL URLWithString:#"file://Something/Application/12345678-1234-1234-1234-123456789ABC/path.tmp"];
// file://Something/Application/B383551F-41C1-4E3D-8EA9-8D76E4AFA919/path.tmp
#endcode
*/
- (nonnull NSURL *)URLByResolvingApplicationDirectoryChange;
#end
#implementation NSURL (App)
- (nonnull NSURL *)URLByResolvingApplicationDirectoryChange {
if (!self.isFileURL) return self;
NSString *pathHome = NSHomeDirectory();
NSString *pathThis = self.path;
if ([pathThis hasPrefix:pathHome]) {
return self;
}
NSArray<NSString *> *cpHome = pathHome.pathComponents;
NSMutableArray<NSString *> *cpThis = pathThis.pathComponents.mutableCopy;
if (cpThis.count < cpHome.count) {
return self;
}
NSInteger i = 0;
for (i = 0; i < cpHome.count - 2; i++) {
NSString *hp = cpHome[i];
NSString *tp = cpThis[i];
if (![hp isEqualToString:tp]) {
return self;
}
}
i++;
NSString *hp = cpHome[i];
NSString *tp = cpThis[i];
if (hp.length != tp.length) {
return self;
}
[cpThis replaceObjectAtIndex:i withObject:hp];
NSString *resolvedPath = [NSString pathWithComponents:cpThis];
return [NSURL.alloc initFileURLWithPath:resolvedPath];
}
#end

Related

Is document directory path constant for iOS device?

I am saving video/image in document directory.Now once the image is saved in document directory I want to save its reference in my local database.So I am thinking I can save URL of the image in the local database.
So is it constant throughout my app?
It's not constant, i have observed every time you launch the app it'll be different, but your data is moved to this new path. You can save your file name in your database, and dynamically append this file name to NSDocument directory.
- (NSString *)documentsFilePath:(NSString *)fileName {
NSArray *dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docsDir = [dirPaths firstObject];
NSString *filePath = [docsDir stringByAppendingPathComponent:fileName];
return filePath;
}
- (void)storeFile:(NSString *)fileName {
NSString *filePath = [self documentsFilePath:fileName];
// create if needed
if (![[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
// Write your data to file system here...
}
}
- (void)deleteFile:(NSString *)fileName {
NSString *filePath = [self documentsFilePath:fileName];
if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
NSError *deleteErr = nil;
[[NSFileManager defaultManager] removeItemAtPath:filePath error:&deleteErr];
if (deleteErr) {
NSLog(#"Can't delete %#: %#", filePath, deleteErr);
}
}
}
Please handle nil checks and store only filename in DB
No, it's not constant. Whenever your app reinstall or updated on device the document directory will change, because when app installed on device os made an directory for app with some random id and each install this random it get changed by OS.
So, you need to make it dynamic own your own, like store the file name only and append the document directory path while using it.
I would suggest only saving the filename or subdirectory/filename (if you have a subdirectory) in the database and then only attaching that to the NSDocumentDirectory.
This will ensure that you always know where the file is...
NSDocumentDirectory is however consistent accross updates, so the files should remain in the document directory even if you update...

What is the hexadecimal part in the Documents folder's path?

I have a file located in my app's Documents folder. When the app is terminated I save the file's URL in the AppDelegate's applicationWillTerminate method:
// archiver init code
[archiver encodeObject:file.URL forKey:kFileURL];
// finish encoding and write data to file system
But when trying to restore the file on the next app launch the file manager cannot locate the file: After calling
NSURL *fileURL = [unarchiver decodeObjectForKey:kFileURL];
NSString *filePath = fileURL.path;
the method
[[NSFileManager defaultManager] fileExists:filePath];
returns NO.
I tried to find the reason for this and I discovered that the path to the Documents folder changes with every app launch. The part that changes is the hexadecimal folder in the middle. Here are two examples:
/private/var/mobile/Applications/04083A4A-87AC-4E3C-8BA1-F002B97AE304/Documents/...
/private/var/mobile/Applications/65D136BA-42C3-887A-B947-7FE396978153/Documents/...
I always thought that the hexadecimal part is some sort of ID unique to every app. But as it changes: What exactly is that number?
And how can I relocate my file then after terminating and relaunching my app?
You should just get the directory for the document folder and then load your file.
+ (NSString *)documentDataPath
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
if ([paths count] == 0) {
return nil;
}
NSString *directory = [paths objectAtIndex:0];
if (directory == nil) {
NSLog(#"NSDocumentDirectory not found!");
}
return directory;
}

NSFileManager not providing correct URLs when calling URLsForDirectory:inDomains:

I want to start off by saying that this block of code worked before the implementation and roll out of iOS 7.
Basically I have a file name that I'm looking for in the NSCachesDirectory, so I create a URL object as my search item. Then I enumerate the directories (using the same NSFileManager object) and look for file names that equal each other, and that's how I know the file exists.
+ (BOOL)itemExistsInMemory:(NSString *)itemName
{
BOOL itemExists = NO;
NSFileManager *fileManager = [[NSFileManager alloc] init];
NSArray *mySandboxDirs = [fileManager URLsForDirectory:NSCachesDirectory inDomains:NSUserDomainMask];//get the directories for the application
NSURL *searchForURL = [[mySandboxDirs lastObject] URLByAppendingPathComponent:[NSString stringWithFormat:#"%#%#", itemName, FileNameAppendix]];//look for the specific file
NSArray *enumerator = [fileManager contentsOfDirectoryAtURL:[mySandboxDirs lastObject] includingPropertiesForKeys:[NSArray arrayWithObjects:NSURLNameKey, NSURLIsRegularFileKey, NSURLCreationDateKey, nil] options:NSDirectoryEnumerationSkipsHiddenFiles error:nil];
for(NSURL *url in enumerator)
{//find out if any of the URLs within the NSCachesDirectory match what we're looking for
NSNumber *isRegularFile = nil;
[url getResourceValue:&isRegularFile forKey:NSURLIsRegularFileKey error:NULL];
if([isRegularFile boolValue])
{
if([url relativeString] isEqualToString:[searchForURL relativeString]])
{
itemExists = YES;
break;
}
}
}
return itemExists;
}
The file DOES INDEED EXIST in the NSCachesDirectory, however, the code doesn't find it because the searchForURL object was created without a path component (the path component is private/...). Why? Even stranger is that I save the data to a URL that's created with the
[[mySandboxDirs lastObject] URLByAppendingPathComponent:[NSString stringWithFormat:#"%#%#", itemName, FileNameAppendix]];
instruction! So it doesn't include the private/ path component in the URL, but when I write the data with [NSData writeToURL:] it "redirects" it to the private/ directory.
So why can't [NSFileManager URLsForDirectory: inDomains:] get me the correct directories for NSCachesDirectory?
More info moved from the comment for better formatting:
By the way, here's an example of what's contained in the URLs I'm creating and looking for ->
When I create a URL for saving:
file:///var/mobile/Applications/C63B378E-5EBE-417C-A465-8C3A3DCE013A/Library/Cac‌​hes/Experimental%20Post.cnt
When I create a URL for searching:
file:///var/mobile/Applications/C63B378E-5EBE-417C-A465-8C3A3DCE013A/Library/Cac‌​hes/Experimental%20Post.cnt
What the enumerator sees:
file:///private/var/mobile/Applications/C63B378E-5EBE-417C-A465-8C3A3DCE013A/Lib‌​rary/Caches/Experimental%20Post.cnt
I could simply take the URLs that the enumerator comes up with and remove the "private" part of the URL so that the strings match and I can proceed, but I'd like to understand why this is happening. Please also note that this only happens when you put the app on an iDevice since the directories are different than when you simulate it with the iOS Simulator.
Thanks to anyone that can be of assistance.
/var is a symlink to /var/private, use [NSURL URLByResolvingSymlinksInPath] to resolve the symlink.
In your example:
for(NSURL *url in enumerator) {
NSURL *resolvedSymlinksURL = [url URLByResolvingSymlinksInPath];
...
}
More detailled discussion: What does the /private prefix on an iOS file path indicate?
in the for loop, see if the url object have some return characters (like \r or \n) and remove it before proceeding.

FileExistAtPath working on Simulator, but not on Device

In my game, I'm saving stats of the player in a plist that I store in the Documents directory. I have an empty dictionary of each stats that should be saved named "Default_Stats.plist" so that if it's the first time the app is loaded, it will copy it in the appropriate directory so it could be loaded and overwritten at will. The problem is, every time my app is loaded, it doesn't recognize the "Stats.plist" and overwrite it with the Default Stats, resetting every stats the player have made... And weird enough, it was perfectly working on the simulator, but not on the device. Here's my code :
In this method I read the stats :
- (void) readStatsFromFile{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *statsPath = [[paths objectAtIndex:0] stringByAppendingPathComponent:#"Stats.plist"];
//Check if the file has already been created
if (![[NSFileManager defaultManager] fileExistsAtPath:statsPath]){
[self createStatsList];
}else{
stats = [[NSMutableDictionary dictionaryWithContentsOfFile:statsPath]retain];
}
}
Here's my creating method :
- (void) createStatsList{
NSString *statsPath = [[NSBundle mainBundle] bundlePath];
statsPath = [statsPath stringByAppendingPathComponent:#"Default_Stats.plist"];
stats = [[NSMutableDictionary dictionaryWithContentsOfFile:statsPath] retain];
[self writeStatsToFile];
}
And my writing method :
- (void) writeStatsToFile{
BOOL ok;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *statsPath = [[paths objectAtIndex:0] stringByAppendingPathComponent:#"Stats.plist"];
ok = [stats writeToFile:statsPath atomically:YES];
if (!ok) {
NSLog(#"Couldn't write to file");
}else
NSLog(#"Stats written succesfully!");
}
Please help, I really don't understand what's wrong! I hope I've made myself clear enough!
Use filepath instead of absolute path.
Maybe duplicates exist in your mac, which makes exists=true on simulator, but not on device.
The easiest way to check would be to NSLog the paths encountered. Refer to these tools - they allow console logs to be captured for release builds running on your device.
Most likely that your documents directory just doesn't exist - on the simulator you share a documents directory with everyone on the Mac; on the device everyone has his own directory. Use the file manager method
createDirectoryAtURL:url withIntermediateDirectories:YES
to make sure that the directory is there before you try writing there. (I tend to use the URL methods instead of the file path methods).
PS. I'd recommend having one method that returns the path or url that you want. It's a good habit not to duplicate your code again and again.
I would do pretty much that, like everything in one session:
gets the URL for the file in the Document folder;
if the file is not there yet, copies the file from bundle to the Documents folder;
that should be the method for that, I have defined some macros for avoiding mistyping the file's name in the code:
- (NSURL *)statsFileURL {
#define NSStringFromFileNameWithExtension(filename, extension) [(filename) stringByAppendingPathExtension:(extension)]
#define kExtension #"plist"
#define kDefaultStatsFileName #"Default_Stats"
#define kCustomStatsFileName #"Stats"
NSURL *_returnURL = nil;
NSFileManager *_fileManager = [NSFileManager defaultManager];
NSURL *_documentDirectory = [[_fileManager URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
NSURL *_myFileURLInDocumentFolder = [_documentDirectory URLByAppendingPathComponent:NSStringFromFileNameWithExtension(kDefaultStatsFileName, kExtension)];
if ([_fileManager fileExistsAtPath:[_myFileURLInDocumentFolder path]]) {
_returnURL = _myFileURLInDocumentFolder;
} else {
NSURL *_myFileURLInBundle = [[NSBundle mainBundle] URLForResource:kDefaultStatsFileName withExtension:kExtension];
if ([_fileManager fileExistsAtPath:[_myFileURLInBundle path]]) {
NSError *_error = nil;
if ([_fileManager copyItemAtURL:_myFileURLInBundle toURL:_myFileURLInDocumentFolder error:&_error]) {
if (_error == nil) {
_returnURL = _myFileURLInDocumentFolder;
} else {
// some error during copying
}
} else {
// some error during copying
}
} else {
// the file does not esixts at all, not even in the bundle
}
}
return _returnURL;
}
the URL always points inside the Documents folder, so you will have read/write access to the file – or will be nil if some error happens.
after you have the URL, you can restore back to file without any issue, and at some other point in runtime you can override the file for your convenience anytime.
NOTE: you may need to extend this code for a more detailed error handling, I put the comment only the places when you need to worry about potential errors.

How to check if a file exists in Documents folder?

I have an application with In-App Purchase, that when the user buy something, download one html file into the Documents folder of my app.
Now I must check if this HTML file exists, so if true, load this HTML file, else load my default html page.
How I can do that? With NSFileManager I can't get outside of mainBundle..
Swift 3:
let documentsURL = try! FileManager().url(for: .documentDirectory,
in: .userDomainMask,
appropriateFor: nil,
create: true)
... gives you a file URL of the documents directory. The following checks if there's a file named foo.html:
let fooURL = documentsURL.appendingPathComponent("foo.html")
let fileExists = FileManager().fileExists(atPath: fooURL.path)
Objective-C:
NSString* documentsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
NSString* foofile = [documentsPath stringByAppendingPathComponent:#"foo.html"];
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:foofile];
Apple recommends against relying on the fileExistAtPath: method. It's often better to just try to open a file and deal with the error if the file does not exist.
NSFileManager Class Reference
Note: Attempting to predicate behavior based on the current state of the file system or a particular file on the file system is not recommended. Doing so can cause odd behavior or race conditions. It's far better to attempt an operation (such as loading a file or creating a directory), check for errors, and handle those errors gracefully than it is to try to figure out ahead of time whether the operation will succeed. For more information on file system race conditions, see “Race Conditions and Secure File Operations” in Secure Coding Guide.
Source: Apple Developer API Reference
From the secure coding guide.
To prevent this, programs often check to make sure a temporary file with a specific name does not already exist in the target directory. If such a file exists, the application deletes it or chooses a new name for the temporary file to avoid conflict. If the file does not exist, the application opens the file for writing, because the system routine that opens a file for writing automatically creates a new file if none exists.
An attacker, by continuously running a program that creates a new temporary file with the appropriate name, can (with a little persistence and some luck) create the file in the gap between when the application checked to make sure the temporary file didn’t exist and when it opens it for writing. The application then opens the attacker’s file and writes to it (remember, the system routine opens an existing file if there is one, and creates a new file only if there is no existing file).
The attacker’s file might have different access permissions than the application’s temporary file, so the attacker can then read the contents. Alternatively, the attacker might have the file already open. The attacker could replace the file with a hard link or symbolic link to some other file (either one owned by the attacker or an existing system file). For example, the attacker could replace the file with a symbolic link to the system password file, so that after the attack, the system passwords have been corrupted to the point that no one, including the system administrator, can log in.
If you set up your file system differently or looking for a different way of setting up a file system and then checking if a file exists in the documents folder heres an another example. also show dynamic checking
for (int i = 0; i < numberHere; ++i){
NSFileManager* fileMgr = [NSFileManager defaultManager];
NSString *documentsDirectory = [NSHomeDirectory() stringByAppendingPathComponent:#"Documents"];
NSString* imageName = [NSString stringWithFormat:#"image-%#.png", i];
NSString* currentFile = [documentsDirectory stringByAppendingPathComponent:imageName];
BOOL fileExists = [fileMgr fileExistsAtPath:currentFile];
if (fileExists == NO){
cout << "DOESNT Exist!" << endl;
} else {
cout << "DOES Exist!" << endl;
}
}
Swift 2.0
This is how to check if the file exists using Swift
func isFileExistsInDirectory() -> Bool {
let paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)
let documentsDirectory: AnyObject = paths[0]
let dataPath = documentsDirectory.stringByAppendingPathComponent("/YourFileName")
return NSFileManager.defaultManager().fileExistsAtPath(dataPath)
}
check if file exist in side the document/catchimage path :
NSString *stringPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];
NSString *tempName = [NSString stringWithFormat:#"%#/catchimage/%#.png",stringPath,#"file name"];
NSLog(#"%#",temName);
if([[NSFileManager defaultManager] fileExistsAtPath:temName]){
// ur code here
} else {
// ur code here**
}
NSArray *directoryPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString *imagePath = [directoryPath objectAtIndex:0];
//If you have superate folder
imagePath= [imagePath stringByAppendingPathComponent:#"ImagesFolder"];//Get docs dir path with folder name
_imageName = [_imageName stringByAppendingString:#".jpg"];//Assign image name
imagePath= [imagePath stringByAppendingPathComponent:_imageName];
NSLog(#"%#", imagePath);
//Method 1:
BOOL file = [[NSFileManager defaultManager] fileExistsAtPath: imagePath];
if (file == NO){
NSLog("File not exist");
} else {
NSLog("File exist");
}
//Method 2:
NSData *data = [NSData dataWithContentsOfFile:imagePath];
UIImage *image = [UIImage imageWithData:data];
if (!(image == nil)) {//Check image exist or not
cell.photoImageView.image = image;//Display image
}
NSURL.h provided - (BOOL)checkResourceIsReachableAndReturnError:(NSError **)error to do so
NSURL *fileURL = [NSURL fileURLWithPath:NSHomeDirectory()];
NSError * __autoreleasing error = nil;
if ([fileURL checkResourceIsReachableAndReturnError:&error]) {
NSLog(#"%# exists", fileURL);
} else {
NSLog(#"%# existence checking error: %#", fileURL, error);
}
Or using Swift
if let url = URL(fileURLWithPath: NSHomeDirectory()) {
do {
let result = try url.checkResourceIsReachable()
} catch {
print(error)
}
}

Resources