Noah
Noah

Reputation: 1429

What is the appropriateFor parameter for in FileManager.url(for:in:appropriateFor:create:)?

Apple's instructions for creating a temporary URL are to use FileManager.url(for:in:appropriateFor:create:). The example they give is (rewritten in Swift 3):

let desktopURL = URL(fileURLWithPath: "/Users/Noah/Desktop/")
do {
    let temporaryDirectoryURL = try FileManager.default.url(for: .itemReplacementDirectory, in: .userDomainMask, appropriateFor: desktopURL, create: true)
} catch {
    // handle error
}

The docs say that the appropriateFor parameter "determines the volume of the returned URL", but I don't understand what that means. What is this parameter for and how should I determine the URL to pass in for it?

Upvotes: 9

Views: 3484

Answers (3)

promacuser
promacuser

Reputation: 396

I came across this today, years later, but the docs have are clear on this now. I don't remember that they were before, but here's your answer direct from the documentation:

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 FileManager.SearchPathDirectory.itemReplacementDirectory and the domain parameter contains the value userDomainMask.

Upvotes: 0

Kang
Kang

Reputation: 63

I Did an experiment to understand it.

let document = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
try? FileManager.default.url(for: .itemReplacementDirectory, in: .userDomainMask, appropriateFor: document, create: true)

A directory appears in sandbox of my app: enter image description here So I think appropriateFor is used to determine where a temporary directory will be created

Upvotes: 0

Scott Thompson
Scott Thompson

Reputation: 23701

The URL that you pass in is used to determine on which Volume (on which mounted disk) the temporary directory will be created. I suspect you should pass a URL to a file or folder that would reside on the same volume.

Upvotes: 2

Related Questions