从 NSString 或 NSUrl 获取网站根目录

发布于 2024-10-04 02:27:49 字数 150 浏览 0 评论 0原文

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

Any ideas how I can get the root of a website from an NSString or an NSURL? So if my URL was http://www.foo.com/bar/baragain how would I get http://www.foo.com/?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

温柔戏命师 2024-10-11 02:27:49

通过使用 [url schema][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

By using [url scheme] and [url host] like so:

NSURL *url = [NSURL URLWithString:@"http://www.foo.com/bar/baragain"];
NSLog(@"Base url: %@://%@", [url scheme], [url host]);
// output is http://www.foo.com
若水般的淡然安静女子 2024-10-11 02:27:49
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/'
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/'
空宴 2024-10-11 02:27:49

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

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

You can remove the NSURL's path from the string. This accounts for port numbers and other data that are part of the root site.

NSString *urlString = @"http://www.foo.com/bar/baragain";
NSURL *rootUrl = [NSURL URLWithString:urlString];
NSString *rootUrlString = [urlString stringByReplacingOccurrencesOfString:rootUrl.path withString:@""];
稀香 2024-10-11 02:27:49
NSString *str = @"http://www.foo.com/bar/baragain"; 
NSArray *temp = [str componentsSeparatedByString: @".com"];
str = [NSString stringWithFormat: @"%@%@", [temp objectAtIndex:0], @".com"];
NSString *str = @"http://www.foo.com/bar/baragain"; 
NSArray *temp = [str componentsSeparatedByString: @".com"];
str = [NSString stringWithFormat: @"%@%@", [temp objectAtIndex:0], @".com"];
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文