27

I have an NSURL, a file path, and I want to add an NSString to the end of it (the file name) how can I do this? But after this is don't I want the entire thing to be an NSURL.

Thanks.

Josh Kahane
  • 16,765
  • 45
  • 140
  • 253

3 Answers3

111

I think it's good solution:

NSURL *bUrl = [aUrl URLByAppendingPathComponent:@"newString"];

In Swift you could do the following,

var bURL = aURL.URLByAppendingPathComponent( "newString" )

You can also state whether the URL is a directory,

var bURL = aURL.URLByAppendingPathComponent( "newString", isDirectory: true )
cjohnson318
  • 3,154
  • 30
  • 33
lyzkov
  • 1,307
  • 1
  • 9
  • 11
8

I think it's as simple as:

    NSString *s = [aUrl.path stringByAppendingString:@"newString"];
Andy Milburn
  • 722
  • 6
  • 13
  • 2
    If you use this, to get an NSURL in the end, you will have to do this: `[NSURL URLWithString:[aUrl.path stringByAppendingString:@"newString"]]` – Myxtic Jul 31 '14 at 04:58
4

If you have a file NSURL to a directory and you want to end up with a NSString containing the NSURL's path with a file name appended to it, use this:

NSURL *url = [NSURL fileURLWithPath:@"/System" isDirectory:YES];
NSString *filename = @"foo";
NSString *result = [url.path stringByAppendingPathComponent:filename];

You can also use URLByAppendingPathComponent but that adds an extra step which creates an extra NSURL object that isn't needed.

NSURL *url = [NSURL fileURLWithPath:@"/System" isDirectory:YES];
NSString *filename = @"foo";
NSURL *newURL = [url URLByAppendingPathComponent:filename];
NSString *result = newURL.path;
Jim Luther
  • 425
  • 4
  • 10