[英]Get root of website from NSString or NSUrl
Any ideas how I can get the root of a website from an NSString or an NSURL? 有关如何从NSString或NSURL获取网站根目录的任何想法? So if my URL was http://www.foo.com/bar/baragain how would I get http://www.foo.com/ ?
所以,如果我的网址是http://www.foo.com/bar/baragain,我将如何获得http://www.foo.com/ ?
By using [url scheme]
and [url host]
like so: 通过使用
[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 = [NSURL URLWithString:@"http://www.foo.com/bar/baragain"];
NSURL *root = [NSURL URLWithString:@"/" relativeToURL:url];
NSLog(@"root = '%@'", root.absoluteString); // root = 'http://www.foo.com/'
You can remove the NSURL
's path
from the string. 您可以从字符串中删除
NSURL
的path
。 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:@""];
NSString *str = @"http://www.foo.com/bar/baragain";
NSArray *temp = [str componentsSeparatedByString: @".com"];
str = [NSString stringWithFormat: @"%@%@", [temp objectAtIndex:0], @".com"];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.