When calling +[NSURL URLWithString:]
I have two options for building my URLs:
[[@"http://example.com" stringByAppendingPathComponent:@"foo"] stringByAppendingPathComponent:@"bar"]
or
[@"http://example.com" stringByAppendingFormat:@"/%@/%@",@"foo",@"bar"];
-[NSString stringByAppendingPathComponent:]
seems like the more correct answer, but do I lose anything using -[NSString stringByAppendingFormat:]
besides handling double-slashes as in the following case?
// http://example.com/foo/bar
[[@"http://example.com/" stringByAppendingPathComponent:@"/foo"] stringByAppendingPathComponent:@"bar"]
// http://example.com//foo/bar oops!
[@"http://example.com/" stringByAppendingFormat:@"/%@/%@",@"foo",@"bar"];
As you're working with URLS, you should use the NSURL
methods:
NSURL * url = [NSURL URLWithString: @"http://example.com"];
url = [[url URLByAppendingPathComponent:@"foo"] URLByAppendingPathComponent:@"bar"]
or in Swift
var url = NSURL.URLWithString("http://example.com")
url = url.URLByAppendingPathComponent("foo").URLByAppendingPathComponent(".bar")
I just ran into a problem with stringByAppendingPathComponent: it removes double slashes everywhere!:
NSString* string1 = [[self baseURL] stringByAppendingString:partial];
NSString* string2 = [[self baseURL] stringByAppendingPathComponent:partial];
NSLog(@"string1 is %s", [string1 UTF8String]);
NSLog(@"string2 is %s", [string2 UTF8String]);
for a baseURl of https://blah.com
and a partial of /moreblah
Produces the two strings:
2012-09-07 14:02:09.724 myapp string1 is https://blah.com/moreblah
2012-09-07 14:02:09.749 myapp string2 is https:/blah.com/moreblah
But for some reason my calls to blah.com to get resource work with the single slash. But it indicates to me that stringByAppendingPathComponent is for paths - NOT urls.
This is on iPhone 4 hardware running iOS 5.1.
I outputted the UTF8 strings as I wanted to make sure that the debugger output I was seeing was believable.
So I guess I am saying - don't use path stuff on URLs, use some home brew or a library.
How about:
[NSString pathWithComponents:@[@"http://example.com", @"foo", @"bar"]]
As pointed out in the comments a /
gets stripped from protocol when using the methods from NSPathUtitlites.h
, so that is the obvious downfall. The solution I could come up with that is closest to the original one I posted is:
[@[ @"http://example.com", @"foo", @"bar" ] componentsJoinedByString:@"/"]
You will just need to use a literal for the path separator which is what NSString
does.
NSString
represents paths generically with ‘/’ as the path separator and ‘.’ as the extension separator.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With