Я пытаюсь получить корневой URL-адрес строки NSString, содержащей URL-адрес.Например, если передан URL-адрес secure.twitter.com
, я хочу получить twitter.com
.Это работает в классе, который я сделал ниже.Однако он не работает для более длинных URL-адресов ...
Вот мой метод:
-
(NSString *)getRootDomain:(NSString *)domain
{
NSString*output = [NSString stringWithString:domain];
if ([output rangeOfString:@"www."].location != NSNotFound)
{
//if the www is still there, get rid of it
output = [domain stringByReplacingOccurrencesOfString:@"www." withString:@""];
}
if ([output rangeOfString:@"http://"].location != NSNotFound)
{
//if the http is still there, get rid of it
output = [domain stringByReplacingOccurrencesOfString:@"http://" withString:@""];
}
if ([output rangeOfString:@"https://"].location != NSNotFound)
{
//if the https is still there, get rid of it
output = [domain stringByReplacingOccurrencesOfString:@"https://" withString:@""];
}
NSLog(@"New: %@",output);
NSArray*components = [output componentsSeparatedByString:@"."];
if ([components count] == 2) //dandy, this is an easy one
{
return output;
}
if ([components count] == 3) //secure.paypal.com
{
NSString*newurl = [NSString stringWithFormat:@"%@.%@",[components objectAtIndex:1],[components objectAtIndex:2]];
return newurl;
}
if ([components count] == 4) //secure.paypal.co.uk
{
NSString*newurl = [NSString stringWithFormat:@"%@.%@.%@",[components objectAtIndex:1],[components objectAtIndex:2],[components objectAtIndex:3]];
return newurl;
}
//Path Components will return the root url in its array in object 0 (usually)
NSArray*path_components = [output pathComponents];
return [path_components objectAtIndex:0];
}
Как я могу заставить эту работу работать для любого URL-адреса?*