dubbeat
dubbeat

Reputation: 7857

Parse domain name from URL string

How would I parse a domain name in Objective-C?

For example if my string value was "http://www.google.com" I would like to parse out the string "google"

Upvotes: 2

Views: 4178

Answers (2)

jhibberd
jhibberd

Reputation: 7476

In iOS 7 you can use the NSURLComponents class:

NSURLComponents *components = [[NSURLComponents alloc] initWithString:@"http://stackoverflow.com/questions/2333972/objective-c-parse-domain-name-from-url-string"];
NSAssert([components.host isEqualToString:@"stackoverflow.com"], nil);

Upvotes: 4

Costique
Costique

Reputation: 23722

I think the question is a tiny bit invalid. A host is determined by its FQDN (fully qualified domain name) which, in your example, is www.google.com. It's not the same as mail.google.com or www.google.info or google.com. To single out "google" is not trivial and does not make much sense from URL perspective.

If you'd like to just parse the URL more-or-less intelligently, I think you can do the following:

  1. Use NSURL's -host method to get the scheme and path/query stripped correctly.
  2. Use NSString's -componentsSeparatedByString: method to get an array of the domain name's "components".
  3. Ignore the last component.
  4. If there's only one component left (or it may be enough to take the second-last component), you're done.
  5. If the first component contains "www" like www3, "ftp", "mail" or something of their kind, you can ignore it too if you like. The rest may be of interest, depending on your needs.
  6. Test your algorithm against ten thousand URLs to get a sense of futility of this task ;)

Upvotes: 7

Related Questions