I am trying to obtain the root url of an NSString containing an url. For example, if the URL passed is secure.twitter.com, I want twitter.com to be returned. This works in the class that I did below. It does not work however for some longer urls...
Here's my method:
-
(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];
}
How can I make this work for any URL?
 
     
     
     
     
     
     
     
    