124

I have an NSURL that looks like this:

file://localhost/Users/myuser/myfile.txt

Is there a standard function to convert it to a local file path looking like this:

/Users/myuser/myfile.txt

2 Answers 2

235

Use the -[NSURL path] method:

NSLog(@"%@", myUrl.path);

From the documentation:

The path of the URL, unescaped with the stringByReplacingPercentEscapesUsingEncoding: method. If the receiver does not conform to RFC 1808, returns nil.

If this URL object contains a file URL (as determined with isFileURL), the return value of this method is suitable for input into methods of NSFileManager or NSPathUtilities. If the path has a trailing slash it is stripped.

Per RFC 3986, the leading slash after the authority (host name and port) portion is treated as part of the path.

Note that you can create such a URL with +[NSURL fileURLWithPath:].

1
  • 9
    Depending where you get the URL from, you may want to check [myURL isFileURL] is true. May 8, 2013 at 12:46
7

Swift 4:

absoluteURL.path 

or

yourUrl.path
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.