Tomasz Szulc
Tomasz Szulc

Reputation: 4235

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?

Upvotes: 1

Views: 642

Answers (1)

user529758
user529758

Reputation:

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.)

Upvotes: 12

Related Questions