NSURL URLWithString:relativeToURL:剪切相对URL

Pip*_*ipo 23 url nsurl ios

我正在尝试实现一个使用RestKit的iOS应用程序.在我到目前为止看到的所有示例中,以下代码用于创建URL:

NSURL *baseURL = [NSURL URLWithString:@"https://api.service.com/v1"];
NSURL *relativeURL = [NSURL URLWithString:@"/files/search" relativeToURL:baseURL];
Run Code Online (Sandbox Code Playgroud)

但随后[relativeURL absoluteString]会回来https://api.service.com/files/search.

所以我尝试了一些例子:

NSURL *baseURL1 = [NSURL URLWithString:@"https://api.service.com/v1/"];
NSURL *baseURL2 = [NSURL URLWithString:@"https://api.service.com/v1"];
NSURL *baseURL3 = [NSURL URLWithString:@"/v1" relativeToURL:[NSURL URLWithString:@"https://api.service.com"]];

NSURL *relativeURL1 = [NSURL URLWithString:@"/files/search" relativeToURL:baseURL1];
NSURL *relativeURL2 = [NSURL URLWithString:@"/files/search" relativeToURL:baseURL2];
NSURL *relativeURL3 = [NSURL URLWithString:@"/files/search" relativeToURL:baseURL3];
NSURL *relativeURL4 = [NSURL URLWithString:@"files/search" relativeToURL:baseURL1];
NSURL *relativeURL5 = [NSURL URLWithString:@"files/search" relativeToURL:baseURL2];
NSURL *relativeURL6 = [NSURL URLWithString:@"files/search" relativeToURL:baseURL3];

NSLog(@"1: %@", [relativeURL1 absoluteString]);
NSLog(@"2: %@", [relativeURL2 absoluteString]);
NSLog(@"3: %@", [relativeURL3 absoluteString]);
NSLog(@"4: %@", [relativeURL4 absoluteString]);
NSLog(@"5: %@", [relativeURL5 absoluteString]);
NSLog(@"6: %@", [relativeURL6 absoluteString]);
Run Code Online (Sandbox Code Playgroud)

这是输出:

1: https://api.service.com/files/search
2: https://api.service.com/files/search
3: https://api.service.com/files/search
4: https://api.service.com/v1/files/search
5: https://api.service.com/files/search
6: https://api.service.com/files/search
Run Code Online (Sandbox Code Playgroud)

所以返回我想要的唯一例子是#4.有谁能解释为什么?

Dai*_*jan 51

我阅读[RFC1808],它定义了解析相对URL的规范算法

2个问题:

  1. 相对URL可能不以/开头,或者它被认为是绝对的:

    Step 4: If the embedded URL path is preceded by a slash "/", the
       path is not relative and we skip to Step 7."
    
    Run Code Online (Sandbox Code Playgroud)
  2. 当基本URL以非斜杠结束时.跳过最后一个斜杠的所有内容

    Step 6: The last segment of the base URL's path (anything
       following the rightmost slash "/", or the entire path if no
       slash is present) is removed and the embedded URL's path is
       appended in its place.  The following operations are
       then applied, in order, to the new path:"
    
    Run Code Online (Sandbox Code Playgroud)

所以这解释了.baseURL需要以/结尾,并且相对url不应该以/开头

  • 再次:最新下来的选民你能不能发表评论,以便我可以根据需要修复它 (3认同)
  • baseURL需要以/结尾,并且相对url不应该以/开头这是绝对正确的:).我正在努力解决基本网址和路径问题.你能为[RFC1808]添加链接吗? (2认同)

Mik*_*lah 9

你有两个问题:

首先,字符串/files/search是一个绝对路径,因为它以斜杠开头.针对任何现有URL解析它将忽略现有路径.

其次,https://api.service.com/v1没有尾部斜杠来表示它是一个目录.针对它解决的任何字符串将始终忽略该v1部分.

总而言之,您需要相对路径的组合files/search- 和目录库URL https://api.service.com/v1/.