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

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"];

Jay is the CEO and founder of WP Hosting, a boutique style managed WordPress hosting and support service. He has been working with Plesk since version 9 and is a qualified Parallels Automation Professional. In his spare time he likes to develop iOS apps and WordPress plugins, or draw on tablet devices. He blogs about his coding journey at and