调用+[NSURL URLWithString:]
时,我有两个构建URL的选项:
[[@"http://example.com" stringByAppendingPathComponent:@"foo"] stringByAppendingPathComponent:@"bar"]
或
[@"http://example.com" stringByAppendingFormat:@"/%@/%@",@"foo",@"bar"];
-[NSString stringByAppendingPathComponent:]
似乎是更正确的答案,但除了像下面的情况那样处理双斜杠外,使用-[NSString stringByAppendingFormat:]
还会损失什么吗?
// http://example.com/foo/bar
[[@"http://example.com/" stringByAppendingPathComponent:@"/foo"] stringByAppendingPathComponent:@"bar"]
// http://example.com//foo/bar oops!
[@"http://example.com/" stringByAppendingFormat:@"/%@/%@",@"foo",@"bar"];
在使用URLS时,应该使用NSURL
方法:
NSURL * url = [NSURL URLWithString: @"http://example.com"];
url = [[url URLByAppendingPathComponent:@"foo"] URLByAppendingPathComponent:@"bar"]
或Swift
var url = NSURL.URLWithString("http://example.com")
url = url.URLByAppendingPathComponent("foo").URLByAppendingPathComponent(".bar")
我刚刚遇到stringByAppendingPathComponent的一个问题:它删除了所有地方的双斜杠!:
NSString* string1 = [[self baseURL] stringByAppendingString:partial];
NSString* string2 = [[self baseURL] stringByAppendingPathComponent:partial];
NSLog(@"string1 is %s", [string1 UTF8String]);
NSLog(@"string2 is %s", [string2 UTF8String]);
对于的基本URLhttps://blah.com
和的一部分
生成两个字符串:
2012-09-07 14:02:09.724 myapp字符串1是https://blah.com/moreblah
2012-09-07 14:02:09.749 myapp字符串2为https://blah.com/moreblah
但出于某种原因,我打电话给blah.com,要求用单斜杠进行资源工作。但它向我表明stringByAppendingPathComponent是用于路径的,而不是URL。
这是在运行iOS 5.1的iPhone 4硬件上。
我输出了UTF8字符串,因为我想确保我看到的调试器输出是可信的。
所以我想我是在说——不要在URL上使用路径,使用一些自制的或库。
怎么样:
[NString pathWithComponents:@[@"http://example.com",@"foo",@"bar"]]
正如评论中所指出的,当使用NSPathUtitlites.h
中的方法时,/
会从协议中剥离,因此这是明显的缺点。我能想出的最接近我发布的原始解决方案是:
[@[ @"http://example.com", @"foo", @"bar" ] componentsJoinedByString:@"/"]
您只需要使用一个文本作为路径分隔符,NSString
就是这样做的。
NSString
一般以"/"作为路径分隔符来表示路径和"。"作为扩展分隔符。
stringByAppendingPathComponent的目的是处理双斜杠,但是,您可以执行以下操作:
[[@"http://example.com/" stringByAppendingPathComponent:[NSString stringWithFormat:@"%@/%@", @"foo", @"bar"]]