LuckyLuke
LuckyLuke

Reputation: 49047

How to get URL for application's document directory iPhone

This code is a part of Core Data. The URLsForDirectory....method does not run on iOS < 4 so I need to know some other methods/objects to call. I would also appriciate documentation for future reference. Thank you

/**
 Returns the URL to the application's Documents directory.
*/
- (NSURL *)applicationDocumentsDirectory
{
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}

Upvotes: 41

Views: 49679

Answers (5)

Amir Khorsandi
Amir Khorsandi

Reputation: 3708

Starting iOS 16.0 you can use:

/// Documents directory for the current user (~/Documents)
/// Complexity: O(n) where n is the number of significant directories
/// specified by `FileManager.SearchPathDirectory`
@available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *)
public static var documentsDirectory: URL { get }

source

Upvotes: 1

Tarik
Tarik

Reputation: 539

Swift 3

let documentsUrl = FileManager.default.urls(for: .documentDirectory, in:.userDomainMask).first!

Upvotes: 20

Paul Ardeleanu
Paul Ardeleanu

Reputation: 6700

Here is the Swift 2.2 version:

let paths = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
let filePath = paths[0].URLByAppendingPathComponent("filename")

Upvotes: 7

stillmotion
stillmotion

Reputation: 4628

An alternative solution would be to use the -[NSFileManager URLsForDirectory:inDomains:] method and fetching the path from the returned NSArray:

Objective-C:

NSArray *paths = [[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask];
NSURL *documentsURL = [paths lastObject];

Swift:

let paths = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
let documentsURL = paths[0] as! NSURL

This is supported in iOS 4.0+

Upvotes: 51

John Parker
John Parker

Reputation: 54415

You can get the document path via the NSSearchPathForDirectoriesInDomains foundation function as follows:

NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentPath = [searchPaths objectAtIndex:0];

This will work on iOS 2+.

Upvotes: 43

Related Questions