Search code examples
objective-curldomain-name

How to get the url domain name with objective-c


When i get a url likehttp://h5.m.abc.com/awp/base/cart.htm?#!/awp/base/cart.htm,I just need the abc.com,what should I do?

EDIT: whatever how the url changes, I only need abc.com, for example:http://h5.m.abc.com.cn/awp/base/cart.htm?#!/awp/base/cart.htm I just needabc.com.cn http://a.b.h.m.abc.cn/awp/base/cart.htm?#!/awp/base/cart.htm I just need abc.cn.


Solution

  • I think this is not the best way, but will work.

      NSString *host = [[NSURL URLWithString:@"http://h5.m.abc.com/awp/base/cart.htm?#!/awp/base/cart.htm"] host];
    
      NSArray  *parts = [host componentsSeparatedByString:@"."];
    
      NSString *justDomain = [NSString stringWithFormat:@"%@.%@",
                          parts[parts.count - 2], parts[parts.count - 1]];
    
      NSLog(@"just domain %@", justDomain);