resolveLocalFileSystemURL on iOS using different App UUID each time - ios

I am using Cordova fileSystem to download some mp3 Audio files thru my App. I am using cordova.file.cacheDirectory and creating a subfolder within that to store the downloaded files. However, the problem is that each time I make some changes and run the App on iPad I get a different path.
The usual pattern is
file:///var/mobile/Containers/Data/Application/13E9EA83-94A2-4950-811E-E491AC176‌​A78/Library/Caches/MyFolder/MyFiles.mp3
However the long number (App UUID) is not consistent. It changes each time I run the App on iPad through Xcode. Because of this I am unable to access, play, delete any files downloaded during the previous session because I am saving the file names with absolute path in a separate file for quick access in the future.

After some R&D I have realized that even though UUID changes each time, it actually refers to the same location. Hence the solution is not to save absolute path and instead, save only the Path beyond "/MyFolder/" in the above example. Each time when the App is run, the Base Path, which is actually file.cordova.cacheDirectory, should be appended to each entry to obtain the absolute Path to the file.

Related

What happens to local files on iOS when the app is updated?

My iOS app is writing to local files to:
/var/mobile/Containers/Data/Application/A.../Library/a.txt
When my app updates, it gets a new application container ID and folder:
/var/mobile/Containers/Data/Application/B...
What happens to all the files I wrote to container ID A?
Is there an "update hook" that will allow me to copy all the "A" container files to path "B"?
Can the new version of the app (B) read the old versions files (A)?
Is there any documentation around what happens to the filesystem during updates?
Is it possible to recover files from container A after B has been installed?
When you update an app, by changing its version number in the .plist file, iOS creates a new directory for that app with a different hexadecimal name and it copies all the files to the new directories. Now if you are using the absolute paths to get the details of files from the directories then those paths would be incorrect and you won't get the file details.
I just tried this in simulator. I created a function as below which will return the document directory path url
func getDocumentsDirectory() -> URL {
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
let documentsDirectory = paths[0]
return documentsDirectory
}
I called this function from didFinishLaunchingWithOptions in app delegate when version number was 1.0 and it returned the below path :
file:///Users/BhargavRathod/Library/Developer/CoreSimulator/Devices/3082611F-BCCA-4D17-B390-E0EF4CA454DA/data/Containers/Data/Application/72759097-38F3-4292-825E-1D2343219973/Documents/
When I updated the version number to 1.1 it returned me the new path as :
file:///Users/BhargavRathod/Library/Developer/CoreSimulator/Devices/3082611F-BCCA-4D17-B390-E0EF4CA454DA/data/Containers/Data/Application/72DC31E9-C32F-42CC-8449-F1946ADB1018/Documents/
So if you are using a absolute path to access any file from document directory then it is not good practice. You can just save the file name(or relative path after the document directory) and whenever the access to that file name is required then get the file name and append it after the document directory path and access the file.
I hope this will be of some help to you.
My iOS app is writing to local files to: /var/mobile/Containers/Data/Application/A.../Library/a.txt
Okay, stop right there. This is wrong.
Your app has its own sandbox. This sandbox persists forever, thru updates, as long as your app keeps its Bundle ID, and as long as the user does not delete the app.
You thus have no business knowing or thinking about the full absolute path to where your file is. All you know, and all you need to know, is that it is in your app’s sandbox in the Library directory. You can, at any time, obtain the URL of the Library directory by means of its search path:
https://developer.apple.com/documentation/foundation/filemanager/searchpathdirectory/librarydirectory
And that is where the file will always be. As long as you ask the FileManager for your Library directory and for the a.txt file within it, you will find the same file, regardless of any updates, as long as the user doesn’t actually delete your app (because that deletes the sandbox).
Can explain what happens to the files
Nothing. They stay where they are within the sandbox. The absolute URL of the sandbox may change, but your files are unaffected.
how to keep the files written by the previous version of the app
They are kept automatically. You don’t have to do anything.
(Having said all that, keep in mind that if you submit an app with a different bundle id, that is not a new version of your app. It is a totally different app. In that case you would have a very different problem to solve. This would be no different from any other problem of communicating files from one app to another. You’d need to put the files in a common location, make them available thru the Document Browser, make them exportable by the user, or whatever.)

Enhance Resilience of Local Storage in Hybrid App

I have developed a hybrid mobile app that has been running on IOS, Android and Chrome reasonably well for over 5 years. My app uses an indexedDB database to maintain the state of the app and save it between restarts, however there are some cases where IOS can clear the indexedDB particularly if the client device is running low on memory.
I would like some help on how to maintain a parallel copy of the indexedDB using the native SQL database on the IOS device, in order to increase the resilience of my app, based on the hopeful expectation that IOS will not arbitrarily decide to clear an internal SQL database belonging to the app.
I understand how to communicate in both directions between Objective C and Javascript but I have not the foggiest idea in Objective C how to:
Create a SQL database in the app file system
Choose where to place the SQL database in the app file system
How to write a new key value pair to the database
Overwrite an existing key value pair in the database
Read back all key value pairs from the database (I expect there could be up to 1000 of these in practice) and pass these efficiently back to the javascript code.
Clear the database and start again.
Any pointers to useful resources on how to achieve this or better still coded examples would be most appreciated.
I would just like to add that I am not using Cordova or any other similar app development environment, so please do not suggest a SQLite plugin that is part of a bigger environment. I have got to where I am with a bespoke coding approach and I would like to keep it that way.
I have explored the idea of paralleling up each indexedDB save with a write to a file in the IOS App Documents Folder with the hope that this is less likely to be wiped than the Caches Folder.
Following each indexedDB setItem with a key-value-pair I pass a request to the objective-C IOS app code to create a text file in a sub folder created with the App Documents Folder, with the name 'key'.txt and the contents set to value.
Following each indexedDB removeItem, I pass a request to the objective-C IOS app code to delete the corresponding text file 'key'.txt.
Following each indexedDB clearAll, I delete the entire sub folder created above.
Now when the app starts up and discovers an empty localForage database, I pass a request to the objective-C IOS app code to test if the sub-folder with key-items is there or not.
If it is not, then this is a fresh install of the app and continue as normal for such a case.
if it is, then this is a case of the indexedDB database having been deleted.
In such case, I request the objective-C IOS app code to return the set of keys, by examining the contents of the folder created above and stripping off the .txt bit and in the case of the IOS Simulator ignoring the DS_Store file.
One by one I then request the contents of each key file and load them back into the previously empty localForage database and when this has been done I can continue as if it had not been deleted.
I found that it is necessary to use a zero duration timeout in the javascript before requesting each value to prevent call stack exceeded errors when restoring large databases.
This approach seems to work and I can test this any time by using the Safari Developer Resources tab actions to clear the database and then manually restarting the app. Using the same tab you can watch the indexedDB database being repopulated.
Due to the size of my database, I actually created a set of sub folders of different types of key, so that I could choose the order in which the database items were restored, especially as my app is often brought back to life in the background following a significant location change and in such cases there is an imposed maximum time limit on how long the app is given to do such a recovery. This refinement is of course optional and only needed for large databases.
The following notes are for anyone who wants to try this approach and assumes using Objective C in XCode 10.1
Use NSHomeDirectory() and stringByAppendingPathComponent #"Documents" to get the Documents folder.
Use stringByAppendingPathComponent to create a sub folder path for the keys sub folder.
Use fileExistsAtPath to check whether the keys sub folder exists already
Use createDirectoryAtPath if it does not.
When saving or changing items in indexedDB use the stringByAppendingPathComponent to create the key file name path e.g. Base.txt for a key of 'Base'.
Use fileHandleforWritingAtPath to get the fileHandle for a file
if fileHandle does not exist then need to create it using writeToFile to create the 'key' file
if fileHandle does exist then truncateFileAtOffseyt:0 (important) to clear it and then use writeData to create a new version of the 'key' file.
In both of the above specify UTF8 encoding.
When removing items from indexedDB do the same to get the key file path and then use removeItemAtPath.
The device can be cleared by removing the entire sub folder using removeItemAtPath.
The restore process uses contentsOfDirectoryAtPath to read the set of keys in the sub folder.
The restore process for each item uses stringWithContentsOfFile to read data files and return the contents enclosed in quotes using a call to stringByEvaluatingJavaScriptFromString
Hope this helps.

Can I save the keep the absolute path of a file in database?

In my app I save some photos in sandbox and I keep its absolute path in database. Then I build and run again, I fetch the path and try to get the photo, it says the file doesn't exist.
At last, I found that every time I build and run my app, the path of app is different.
I use NSTemporaryDirectory() to get the temporary path, I run two times and get two results.
/private/var/mobile/Applications/80E09BB5-5FEB-4C27-935E-E29DE7861392/tmp/
/private/var/mobile/Applications/71427100-0DBF-42F0-B6B4-F88F6417292E/tmp/
Is it normal? When user updates my app, will the absolute path change?
If it's normal, should I just keep the relative path in database? Is there some best practice?
It's a very bad idea to store the absolute path in the database as any updates to the app results in the app being stored in a different folder within /private/var/mobile/Applications. During an app update, any files will be migrated across, however any references to them within the database will no longer be valid.
You must therefore always store the filepath relative to some other logical directory; for example the Documents or Caches folder.
This probably means you should store this path as a relative directory within your classes as well, and only resolve to an absolute path when you need to use it.
Finally storing temporary file references is probably a bad idea, as I believe any temporary or cached files can be removed from the filesystem by the O/S whenever it feels like it. Therefore you should store these files in the Documents folder, using the techniques I mentioned above.
You could save the file on server and store its physical path in database. I have built similar applications in past and that is how i used it. Might not be the right way but just a thought.
Is it normal?
Well, what is the meaning of temporary?
When user updates my app, will the absolute path change?
Well, what is the meaning of temporary?
If it's normal, should I just keep the relative path in database?
To do what with it?
Is there some best practice?
Don't use a temporary path for persistent storage. What about the documents folder?

How does one handle container directories on iOS?

I am working on an app that saves files to the documents directory, and then saves an absolute path for each of those files in an entity using core data. The issue is that each time I rebuild and run my app on my device, the app is saved in a different generated directory, and those file paths are now incorrect. However, my documents directory is still preserved.
I have three questions about this:
If an app is updated on the store, does it then go in a different generated directory, thus invalidating any absolute paths that could be saved in the documents directory?
This is extremely unlikely but is there any way to specify in Xcode to build the app to the same directory the previous build was in?
Is there a way to specify in Xcode that you would like all documents and data wiped with each new build you load on the device?
Thanks everyone!
You said:
"I am working on an app that saves files to the documents directory, and then saves an absolute path for each of those files in an entity using core data."
Don't do that. Ever. The path to your documents directory will be different on different devices, and different if you delete your app and reinstall it. Absolute paths are pretty much guaranteed to fail.
Use paths relative to the sandbox directory in question (documents directory, temp directory, etc)

App Updates, NSURL, and Documents Directory

I have an app in the app store that uses Core Data to persist much of the data.
The exception is storing images. I store images in subdirectories to the Documents directory and store an NSURL reference to that image in the appropriate object attribute in the core data store.
We have noticed that, when an update makes it to the app store, those images are not found, and thus don't display, using the references stored with the previous version of the app.
Now, I have a suspicion that the problem is that, since we are using development devices for testing, this issue propagates because the Directory in the Applications directory to which the dev app uses differs from the one the App store is creating/using. I have noticed differences between the App store directory for the app in Applications and the one created while debugging versions in Xcode.
As such, the URL stored in core data points to the wrong applications folder.
This is kinda hard to debug, as I cannot download an older app version, once the new version has been released in the store.
So I have a couple questions. Can I guarantee that the Applications subdirectory in which folks who download versions of the same app will be the same, rendering this a non-issue for non-development devices?
Should I be storing relative image url's or strings to represent the location of these resources, or should I be fine with storing what ends up being the absolute urls?
Thanks so much,
Felipe
You should use relative URLs to store references to files. The absolute URL is likely to change after an app update
Files Saved During App Updates
When a user downloads an app update,
iTunes installs the update in a new app directory. It then moves the
user’s data files from the old installation over to the new app
directory before deleting the old installation. Files in the following
directories are guaranteed to be preserved during the update process:
Application_Home/Documents
Application_Home/Library
Although files
in other user directories may also be moved over, you should not rely
on them being present after an update.
https://developer.apple.com/library/ios/#DOCUMENTATION/iPhone/Conceptual/iPhoneOSProgrammingGuide/PerformanceTuning/PerformanceTuning.html
Thx to the sandbox, the application home is also the user home. So it is possible to use the unix tilde which is a short hand to the user home, i.e. ~/Documents, ~/Library and so on.
Use -[NSString stringByAbbreviatingWithTildeInPath] to turn a full path into a relative ~ path. And reverse it with -[NSString stringByExpandingTildeInPath].
I think what you're looking for is the following:
NSString *appDocumentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];

Resources