Search code examples
macoscocoansstringnsurl

What’s the correct way to create an NSURL from an NSString?


I’ve got an NSString that stores the path to a saved file:

NSString *filePath = [NSString stringWithFormat:
                      @"%@/someFolder/%@",
                      NSHomeDirectory(),
                      [NSString stringWithFormat:@"%@",[self.fileName stringByAppendingPathExtension:@"txt"]]];

And it’s OK — when I log it, I get:

/Users/username/someFolder/fileName.txt

So my next step is to make an NSURL object from this NSString. I did this:

        NSURL *pathURL = [NSURL URLWithString:[NSString stringWithFormat:@"%@", filePath]];
        NSLog(@"URL = %@", pathURL);

but the response is:

URL = (null)

What’s wrong here? How can I do this correctly?


Solution

  • A path is not a valid URL by itself. You have to use this:

    NSURL *pathURL = [NSURL fileURLWithPath:filePath];
    

    And read the documentation. (And don’t overuse / abuse format strings.)