How to convert a file path into an NSURL (and back)

- by

To convert a file path into an NSURL:

NSURL *localURL = [NSURL fileURLWithPath:localPath];

To create a local path from an NSURL:

NSString *localPath = [localURL filePathURL];

NSURLs can also be created directly from an NSString:

NSURL *yourURL = [[NSURL alloc]initWithString:@""];
// or
NSURL *yourURL = [NSURL URLWithString:@""];

If you’re ever tried to pass a local path into this method you’ll have noticed that it doesn’t work. Use the above methods instead.

You can also add path components to a URL, for example to reference your Documents directory:

// create a path and append a component
NSString *path = NSHomeDirectory();
path = [path stringByAppendingPathComponent:@"Documents"];

will give something like


NSURLs have the same method called URLByAppendingPathComponent:

NSURL *myURL = [NSURL URLWithString:path];
myURL = [myURL URLByAppendingPathComponent:@"MyDirectory"];

If you enjoy my content, please consider supporting me on Ko-fi. In return you can browse this whole site witout any pesky ads! More details here.

Add your voice!

This site uses Akismet to reduce spam. Learn how your comment data is processed.