Search code examples
iosswiftxcodensurl

How to get top level domain name of URL in swift 4?


My requirement is to get domain name of URL by filtering out it's subdomain name.

i can get host name by using code as below

if let url = URL(string: "https://blog.abc.in/")  {
    if let hostName = url.host  {
         print("host name = \(hostName)") // output is: blog.mobilock.in
    }
 }

so here in URL blog is a subdomain and abc is a domain name, I wish to know/print only abc by excluding its subdomain parts.

In android, there is a class InternetDomainName which return domain name, the similar solution I am looking for iOS

I tried several answers and it's not duplicate of any or some of them is not working or that is a workaround.

Get the domain part of an URL string?


Solution

  • So finally i found better and standard approach for this issue -

    Mozilla volunteers maintain Public Suffix List and there you can find list of library for respective language. so in list Swift library is also present. At the time of writing this answer Swift library don't have provison of adding it through CocoPods so you have to add downloaded project directly into your project. Code to get TLD name assuming Swift library is added into your project.

    import DomainParser
    
    static func getTLD(withSiteURL:String) -> String? {
            do{
                let domainParse = try DomainParser()
                if let publicSuffixName = domainParse.parse(host: withSiteURL)?.publicSuffix {
                    if let domainName = domainParse.parse(host: withSiteURL)?.domain {
    
                        let tldName = domainName.replacingOccurrences(of: publicSuffixName, with: "").replacingOccurrences(of: ".", with: "")
                        print("top level name = \(tldName)")
                        return tldName
                    }
                }
            }catch{
            }
            return nil
        }
    

    Add Domain parser library as sub-project of your project, as pod of this library is not available yet