Instance Method

url(for:in:appropriateFor:create:)

Locates and optionally creates the specified common directory in a domain.

Declaration

func url(for directory: FileManager.SearchPathDirectory, in domain: FileManager.SearchPathDomainMask, appropriateFor url: URL?, create shouldCreate: Bool) throws -> URL

Parameters

directory

The search path directory. The supported values are described in FileManager.SearchPathDirectory.

domain

The file system domain to search. The value for this parameter is one of the constants described in FileManager.SearchPathDomainMask. You should specify only one domain for your search and you may not specify the allDomainsMask constant for this parameter.

url

The file URL used to determine the location of the returned URL. Only the volume of this parameter is used.

This parameter is ignored unless the directory parameter contains the value itemReplacementDirectory and the domain parameter contains the value userDomainMask.

shouldCreate

Whether to create the directory if it does not already exist.

When creating a temporary directory, this parameter is ignored and the directory is always created.

Return Value

The NSURL for the requested directory.

Discussion

You typically use this method to locate one of the standard system directories, such as the Documents, Application Support or Caches directories. After locating (or creating) the desired directory, this method returns the URL for that directory. If more than one appropriate directory exists in the specified domain, this method returns only the first one it finds.

You can use this method to create a new temporary directory. To do so, specify itemReplacementDirectory for the directory parameter, userDomainMask for the domain parameter, and a URL for the url parameter which determines the volume of the returned URL.

For example, the following code results in temporaryDirectoryURL with a value in the form of /private/var/folders/d0/h37cw8ns3h1bfr_2gnwq2yyc0000gn/T/TemporaryItems/Untitled/:

let desktopURL = NSURL(fileURLWithPath: "/Users/jappleseed/Desktop/")
do {
    let temporaryDirectoryURL = try NSFileManager.defaultManager().URLForDirectory(.ItemReplacementDirectory, inDomain: .UserDomainMask, appropriateForURL: desktopURL, create: true)
} catch {
    // handle the error
}

See Also

Locating System Directories

func urls(for: FileManager.SearchPathDirectory, in: FileManager.SearchPathDomainMask)

Returns an array of URLs for the specified common directory in the requested domains.