What's the Best Way to Find the User's Documents Directory on an Iphone

What's the best way to find the user's Documents directory on an iPhone?

Objc:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)

Swift:

var paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)

You'll want the first element of the returned array.

User specific Documents directory on iOS device

From Apple Documentation

Where You Should Put Your App’s Files

Put user data in Documents/. User data generally includes any files you might want to expose to the user—anything you might want the user to create, import, delete or edit. For a drawing app, user data includes any graphic files the user might create. For a text editor, it includes the text files. Video and audio apps may even include files that the user has downloaded to watch or listen to later.

Put app-created support files in the Library/Application support/ directory. In general, this directory includes files that the app uses to run but that should remain hidden from the user. This directory can also include data files, configuration files, templates and modified versions of resources loaded from the app bundle.

Remember that files in Documents/ and Application Support/ are backed up by default. You can exclude files from the backup by calling -[NSURL setResourceValue:forKey:error:] using the NSURLIsExcludedFromBackupKey key. Any file that can be re-created or downloaded must be excluded from the backup. This is particularly important for large media files. If your application downloads video or audio files, make sure they are not included in the backup.

Put temporary data in the tmp/ directory. Temporary data comprises any data that you do not need to persist for an extended period of time. Remember to delete those files when you are done with them so that they do not continue to consume space on the user’s device. The system will periodically purge these files when your app is not running; therefore, you cannot rely on these files persisting after your app terminates.

Put data cache files in the Library/Caches/ directory. Cache data can be used for any data that needs to persist longer than temporary data, but not as long as a support file. Generally speaking, the application does not require cache data to operate properly, but it can use cache data to improve performance. Examples of cache data include (but are not limited to) database cache files and transient, downloadable content. Note that the system may delete the Caches/ directory to free up disk space, so your app must be able to re-create or download these files as needed.

What is the documents directory (NSDocumentDirectory)?

Your app only (on a non-jailbroken device) runs in a "sandboxed" environment. This means that it can only access files and directories within its own contents. For example Documents and Library.

See the iOS Application Programming Guide.

To access the Documents directory of your applications sandbox, you can use the following:

iOS 8 and newer, this is the recommended method

+ (NSURL *)applicationDocumentsDirectory
{
return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}

if you need to support iOS 7 or earlier

+ (NSString *) applicationDocumentsDirectory 
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *basePath = paths.firstObject;
return basePath;
}

This Documents directory allows you to store files and subdirectories your app creates or may need.

To access files in the Library directory of your apps sandbox use (in place of paths above):

[NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) objectAtIndex:0]

There's a way to access the document folder in iphone/ipad (real device, no simulator)?

To anyone looking out for the exact answer:-

1.Go to plist file of your project.

2.Add one row.

3.Then set the Boolean value of the property "Application supports iTunes file sharing" to "YES". (the key name is UIFileSharingEnabled)

And you are good to go.

Also note that you have to plugin the device in order to access the copied files (Programmatically). If you happen to go and try to access it on computer .. you wont be able to find the files.

(iphone) access device's documents directory from mac?

You can open Organizer in Xcode and download the documents directory when your device is connected right ?

Getting list of files in documents folder

This solution works with Swift 4 (Xcode 9.2) and also with Swift 5 (Xcode 10.2.1+):

let fileManager = FileManager.default
let documentsURL = fileManager.urls(for: .documentDirectory, in: .userDomainMask)[0]
do {
let fileURLs = try fileManager.contentsOfDirectory(at: documentsURL, includingPropertiesForKeys: nil)
// process files
} catch {
print("Error while enumerating files \(documentsURL.path): \(error.localizedDescription)")
}

Here's a reusable FileManager extension that also lets you skip or include hidden files in the results:

import Foundation

extension FileManager {
func urls(for directory: FileManager.SearchPathDirectory, skipsHiddenFiles: Bool = true ) -> [URL]? {
let documentsURL = urls(for: directory, in: .userDomainMask)[0]
let fileURLs = try? contentsOfDirectory(at: documentsURL, includingPropertiesForKeys: nil, options: skipsHiddenFiles ? .skipsHiddenFiles : [] )
return fileURLs
}
}

// Usage
print(FileManager.default.urls(for: .documentDirectory) ?? "none")

Document directory path of Xcode Device Simulator

on my computer, the path is:

~/Library/Developer/CoreSimulator/Devices/1A8DF360-B0A6-4815-95F3-68A6AB0BCC78/data/Container/Data/Application/

NOTE: probably those long IDs (i.e UDIDs) are different on your computer.

Sharing data in the documents directory in iPhone and Watch app

After you've configured your App Group in Xcode (see the section on Sharing Data with Your Containing iOS App), you can obtain a path to the shared container/folder like this:

NSURL *groupContainerURL = [[NSFileManager defaultManager]
containerURLForSecurityApplicationGroupIdentifier:@"YourAppGroupIdentifier"];
NSString *sharedDirectory = [groupContainerURL path];

Then, to write a UIImage (for example) to that folder:

NSData *imageData = UIImagePNGRepresentation(image);
NSString *filePath = [sharedDirectory stringByAppendingPathComponent:@"image.png"];
[imageData writeToFile:filePath atomically:YES];

You can use the same logic in both your Watch extension and iOS app to share files. You can also create your own directories, as there is no "standard" directory structure for shared containers.

Do users have access to the Documents directory in an iOS sandbox?

I'm not an iOS security expert, however, I can share my experience of working with users data on iOS. Any corrections/remarks are appreciated.

Generally speaking, the best recommendation would be to store important user's data remotely (i.e. having a server backend or using iCloud) with SSL-protected connection. However, if you are forced to store data locally for some reason, here are some recommendations:

1) Do not ever save important data in Documents directory or in NSUserDefaults as is. It's pretty easily accessible for user even on non-jailbroken devices. For instance, you can check iExplorer: as far as I remember, it does the trick.

2) If you really need to store some data locally, whatever your choice is: Documents folder, UserDefaults or CoreData, you have to encrypt it. Algorithm choice is up to you, but it's better to use some iOS built-in solution for it.

3) The data encryption assumes having a key for your app to decrypt it. The best way to store your key is KeyChain. Probably, that is the only place where you can store keys and other stuff like user's authorization data with no worries of being stolen from the outside.

Eventually, after all these steps your user's encrypted data can still be accessible by user. One won't be able to read it unless it is encrypted, but having access to the own keychain and some skill, an advanced user can finally get the original data. Moreover, it still can be damaged. So, in terms of saving data from being damaged or removed you still need to store backups or the data itself somewhere remotely.



Related Topics



Leave a reply



Submit