【问题标题】:Get root of website from NSString or NSUrl从 NSString 或 NSUrl 获取网站的根目录
【发布时间】:2011-05-14 21:30:10
【问题描述】:

有什么想法可以从 NSString 或 NSURL 获取网站的根目录吗?因此,如果我的网址是 http://www.foo.com/bar/baragain,我将如何获得 http://www.foo.com/

【问题讨论】:

    标签: ios cocoa nsurl


    【解决方案1】:

    您可以从字符串中删除NSURLpath。这说明了作为根站点一部分的端口号和其他数据。

    NSString *urlString = @"http://www.foo.com/bar/baragain";
    NSURL *rootUrl = [NSURL URLWithString:urlString];
    NSString *rootUrlString = [urlString stringByReplacingOccurrencesOfString:rootUrl.path withString:@""];
    

    【讨论】:

    • 太棒了!谢谢。
    • @Hafthor 你是对的 - 这仍然不正确。随意编辑。
    【解决方案2】:
    NSURL *url = [NSURL URLWithString:@"http://www.foo.com/bar/baragain"];
    NSURL *root = [NSURL URLWithString:@"/" relativeToURL:url];
    NSLog(@"root = '%@'", root.absoluteString); // root = 'http://www.foo.com/'
    

    【讨论】:

      【解决方案3】:
      NSString *str = @"http://www.foo.com/bar/baragain"; 
      NSArray *temp = [str componentsSeparatedByString: @".com"];
      str = [NSString stringWithFormat: @"%@%@", [temp objectAtIndex:0], @".com"];
      

      【讨论】:

      • 任何人都可以让我知道否决我的答案
      • 为什么这被否决了?这是错误的,想象一个像http://www.computer.com/ Btw 这样的网址,这不是我。
      • 雪利酒,我没有对你投反对票。我确实同意fluchtpunkt,但您的解决方案不能解决.com以外的任何问题,但是我不太清楚我的问题中是否需要它。我给出的示例可能会让您认为我只希望 .com 使用它。
      • 没关系。我也在学习过程中。如果我们在某个地方错了,我感谢人们在这里纠正我们
      • 一个好的解决方案应该能够解决ftp://user:pass@whatever.here.host.org:8080之类的问题。
      【解决方案4】:

      像这样使用[url scheme][url host]

      NSURL *url = [NSURL URLWithString:@"http://www.foo.com/bar/baragain"];
      NSLog(@"Base url: %@://%@", [url scheme], [url host]);
      // output is http://www.foo.com
      

      【讨论】:

      • 这不是通用的,因为也可以有用户名和密码……这是更好的解决方案:“我发现的另一种方法是 NSURL 包含路径方法。我可以得到路径,然后从完整的 URL 中减去它,我就得到了我想要的。”
      • 是的,如果那里也有端口,减去路径会更安全
      猜你喜欢
      • 2012-02-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-03
      • 2023-03-03
      • 2012-09-25
      • 1970-01-01
      相关资源
      最近更新 更多