是否可以仅从 NSURL 获取域和 TLD?没有www或其他什么? [英] Is it possible to just get the domain and TLD from an NSURL? No www or anything else?
本文介绍了是否可以仅从 NSURL 获取域和 TLD?没有www或其他什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有 http://www.youtube.com
、http://youtube.com
和 https://www1.youtube.com/moretext
.我将如何编写检查以查看所有这些网址是否都来自 youtube.com?
Say I have http://www.youtube.com
, http://youtube.com
, and https://www1.youtube.com/moretext
. How would I write a check to see if all of those URLs are from youtube.com?
我尝试了 url.host
并且它似乎保留了 www.
和诸如此类的东西,这不是我想要的.
I tried url.host
and it seems to keep the www.
and whatnot, which is not what I want.
我基本上只想说:
if ([url isFromWebsite:@"youtube.com"]) {
// Do things.
}
这可能吗?
推荐答案
这是 NSURL
上未经测试的类别,它将提供您想要的方法.
Here’s an untested category on NSURL
that will provide the method you want.
@implementation NSURL (IsFromWebsite)
- (BOOL) isFromWebsite:(NSString *)domain
{
NSArray *selfHostComponents = [[self host] componentsSeparatedByString:@"."];
NSArray *targetHostComponents = [domain componentsSeparatedByString:@"."];
NSInteger selfComponentsCount = [selfHostComponents count];
NSInteger targetComponentsCount = [targetHostComponents count];
NSInteger offset = selfComponentsCount - targetComponentsCount;
if (offset < 0)
return NO;
for (NSUInteger i = offset; i < selfComponentsCount; i++) {
if (![selfHostComponents[i] isEqualToString:targetHostComponents[i - offset]])
return NO;
}
return YES;
}
@end
另一种(同样未经测试的)方法来做同样的事情,正如 Jesse Rusak 所建议的:
Another (also untested) way to do the same thing, as suggested by Jesse Rusak:
@implementation NSURL (IsFromWebsite)
- (BOOL) isFromWebsite:(NSString *)domain
{
NSArray *selfComponents = [[self host] componentsSeparatedByString:@"."];
NSArray *targetComponents = [domain componentsSeparatedByString:@"."];
NSInteger sizeDifference = [selfComponents count] - [targetComponents count];
if (sizeDifference < 0)
return NO;
return [[selfComponents subarrayWithRange:NSMakeRange(sizeDifference, [targetComponents count])]
isEqualToArray:targetComponents];
}
@end
这篇关于是否可以仅从 NSURL 获取域和 TLD?没有www或其他什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文