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?
A Second Level Domain (SLD) is the part of the domain name that is located right before a Top Level Domain (TLD). For example, in mozilla.org the SLD is mozilla and the TLD is org .
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
It is just a workaround but works perfectly:
if let url = URL(string: "https://x.y.z.a.b.blog.mobilock.in/") {
if let hostName = url.host {
print("host name = \(hostName)") // output is: x.y.z.a.b.blog.mobilock.in
let subStrings = hostName.components(separatedBy: ".")
var domainName = ""
let count = subStrings.count
if count > 2 {
domainName = subStrings[count - 2] + "." + subStrings[count - 1]
} else if count == 2 {
domainName = hostName
}
print(domainName)
}
}
Let me know if you face any issue.
There is no simple way, regardless of language. See How to extract top-level domain name (TLD) from URL for some good discussion of the difficulties involved.
To fetch the root domain of a URL, you can use the following URL
extension:
extension URL {
var rootDomain: String? {
guard let hostName = self.host else { return nil }
let components = hostName.components(separatedBy: ".")
if components.count > 2 {
return components.suffix(2).joined(separator: ".")
} else {
return hostName
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With