今天遇到了一些奇怪的事情,也许有一个简单的解释。
如果我使用最初相对于作为子目录的基本 URL 构造的 NSURL 创建 NSURLRequest,则 NSURLRequest 会删除子目录。
这更容易用代码解释:
// create a base URL to work with
NSURL *baseUrl = [NSURL URLWithString:@"http://www.google.com/sub"];
// create a URL relative to the base URL
NSURL *url1 = [NSURL URLWithString:@"/foo/bar" relativeToURL:baseUrl];
// create a NSURLRequest using this first URL
NSURLRequest *mangled_req = [[NSURLRequest alloc] initWithURL:url1];
NSLog(@"url1: %@", url1);
NSLog(@"mangled_req: %@", mangled_req);
// now create another URL that puts the base URL together with the relative path
NSURL *url2 = [NSURL URLWithString:@"http://www.google.com/sub/foo/bar"];
// and create a NSURLRequest, which should be the same as above
NSURLRequest *correct_req = [[NSURLRequest alloc] initWithURL:url2];
NSLog(@"url2: %@", url2);
NSLog(@"correct_req: %@", correct_req);
输出证明了这一点:
2013-01-25 11:55:37.386 url1: /foo/bar -- http://www.google.com/sub
2013-01-25 11:55:37.408 mangled_req: <NSURLRequest http://www.google.com/foo/bar>
2013-01-25 11:55:37.409 url2: http://www.google.com/sub/foo/bar
2013-01-25 11:55:37.409 correct_req: <NSURLRequest http://www.google.com/sub/foo/bar>
请注意,“mangled_req”省略了 /sub。
这让我现在很烦,因为我正在使用 AFNetworking 并且想要在 localhost 之间切换以进行测试(它自然将我的 Web 应用程序放在一个子目录中)和远程服务器(它没有)。
当然有解决方法,但这对我来说似乎很奇怪,我一定做错了什么。