Objective-C – Convert NSString File Path to NSURL and Vice Versa

Convert NSString to NSURL

NSURL *fileURL = [[NSURL alloc] initFileURLWithPath:filePath];
/* OR */
NSURL *fileURL = [NSURL fileURLWithPath:filePath];

 

Convert NSURL to NSString

// The output string will have the file:// prefix
NSString *filePath= [fileURL absoluteString];

// The output string will have the file path only
NSString *filePath= [fileURL path];

 

Updated @ 2011-01-10: Thanks for the comments of Brandon and Antal.

About these ads

6 thoughts on “Objective-C – Convert NSString File Path to NSURL and Vice Versa”

  1. Converting a NSURL to a NSString File Path is:

    NSString *filePath = [fileURL path];

    The code you have that uses -absoluteString results in a string that has the “file://” prefix.

    Like

    1. I have just spent half an hour trying to figure out what’s wrong with my code, using the methods above — then I have seen the comment….

      ykyuen, maybe you could correct the post, so that others wouldn’t have the same problem in the future.

      Like

  2. Minor point – but you’re missing the pointer * in the second example for converting NSString to NSURL.

    NSURL fileURL = [NSURL fileURLWithPath:filePath];

    should be

    NSURL *fileURL = [NSURL fileURLWithPath:filePath];

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s