objective c - Retrieve Root URL - NSString -


i trying obtain root url of nsstring containing url. example, if url passed secure.twitter.com, want twitter.com returned. works in class did below. not work longer urls...

here's method:

-

(nsstring *)getrootdomain:(nsstring *)domain {     nsstring*output = [nsstring stringwithstring:domain];      if ([output rangeofstring:@"www."].location != nsnotfound)     {     //if www still there, rid of     output = [domain stringbyreplacingoccurrencesofstring:@"www." withstring:@""];     }      if ([output rangeofstring:@"http://"].location != nsnotfound)     {     //if http still there, rid of     output = [domain stringbyreplacingoccurrencesofstring:@"http://" withstring:@""];     }      if ([output rangeofstring:@"https://"].location != nsnotfound)     {     //if https still there, rid of     output = [domain stringbyreplacingoccurrencesofstring:@"https://" withstring:@""];     }      nslog(@"new: %@",output);      nsarray*components = [output componentsseparatedbystring:@"."];      if ([components count] == 2) //dandy, easy 1     {         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 return root url in array in object 0 (usually)      nsarray*path_components = [output pathcomponents];        return [path_components objectatindex:0]; } 

how can make work url?

you consider taking advantage of nsurl , nsstring this, so:

(nsstring *)getrootdomain:(nsstring *)domain {     // return nil if none found.     nsstring * rootdomain = nil;      // convert string nsurl take advantage of nsurl's parsing abilities.     nsurl * url = [nsurl urlwithstring:domain];      // host, e.g. "secure.twitter.com"     nsstring * host = [url host];      // separate host constituent components, e.g. [@"secure", @"twitter", @"com"]     nsarray * hostcomponents = [host componentsseparatedbystring:@"."];     if ([hostcomponents count] >=2) {         // create string out of last 2 components in host name, e.g. @"twitter" , @"com"         rootdomain = [nsstring stringwithformat:@"%@.%@", [hostcomponents objectatindex:([hostcomponents count] - 2)], [hostcomponents objectatindex:([hostcomponents count] - 1)]];     }      return rootdomain; } 

Comments

Popular posts from this blog

apache - Add omitted ? to URLs -

redirect - bbPress Forum - rewrite to wwww.mysite prohibits login -

php - How can I stop spam on my custom forum/blog? -