【问题标题】:Host of an NSURL without the subdomains没有子域的 NSURL 的主机
【发布时间】:2011-06-24 20:42:07
【问题描述】:
如何获取没有子域的 NSURL 的主机?
这里有一些输入。
应该保留的部分用粗体表示,应该去掉的部分用斜体表示:
server.com
www.server.com
media. server.com
host1.media.server.com
到目前为止,听起来很容易实现。
但它也应该正确处理以下输入,以及任何我没有想到的奇怪情况,这些情况在任何相关 RFC 中被普遍接受或指定。
server.co.uk
media.server.co.uk
127.0.0.1强>
...
【问题讨论】:
标签:
cocoa
subdomain
nsurl
【解决方案1】:
这并不能回答难题,但是如果您将 URL 与特定域的白名单匹配(就像我发现这个问题时那样),您可以使用这样的代码来检查:
NSArray *domainsForVideo = @[@"youtube.com",
@"youtu.be",
@"videoschool.pvt.k12.md.us",
@"vimeo.com"];
NSString *host = [url host]; //where URL is some NSURL object
BOOL hostMatches = NO;
for (NSString *testHost in domainsForVideo) {
if ([[host lowercaseString] isEqualToString:testHost]) hostMatches = YES; // matches youtube.com exectly
NSString *testSubdomain = [NSString stringWithFormat:@".%@",testHost]; // matches www.youtube.com but not fakeyoutube.com
if ([[host lowercaseString] rangeOfString:testSubdomain].location != NSNotFound) hostMatches = YES;
}
if (hostMatches) {
// this is a Video URL
}