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:@"http://wpguru.co.uk"];
// or
NSURL *yourURL = [NSURL URLWithString:@"http://wpguru.co.uk"];

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

/var/mobile/Applications/FCEB24E4-7705-4DE2-ABE8-3B50C717A483/Documents

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 without any pesky ads! More details here.

Leave a Comment!

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