Brett
Brett

Reputation: 4166

How to get the path/directory component from a NSURL?

I retrieved a NSURL from a NSSavePanel. I now have this NSURL which gives me the following:

file://localhost/Users/brett/Documents/asdf%20asdf.json

Now, it is easy for me to retrieve just the filename using something like the following:

[[[NSFileManager defaultManager] displayNameAtPath:pathAndFilename] stringByDeletingPathExtension]

This gives me just the localized filename, as expected: asdf%20asdf

So, how do I get the path, like so: file://localhost/Users/brett/Documents/

Upvotes: 16

Views: 18827

Answers (3)

Kibernetik
Kibernetik

Reputation: 3028

Directly from your NSSavePanel:

NSSavePanel *savePanel;
...
NSString *path = savePanel.directoryURL.path;

Upvotes: 1

Mike Abdullah
Mike Abdullah

Reputation: 15013

-[NSURL URLByDeletingLastPathComponent] is the simplest way to achieve this.

Upvotes: 36

Nekto
Nekto

Reputation: 17877

You could use NSString methods to work with file paths. For example,

NSString *directory = [[URL absoluteString] stringByDeletingLastPathComponent];
NSString *filename = [[URL absoluteString] lastPathComponent];

You could find other useful methods in Apple Docs: NSString Class Reference -> Working with Paths section

Upvotes: 28

Related Questions