gpt4 book ai didi

ios - 如何在 swift 4 中获取 URL 的顶级域名?

转载 作者:可可西里 更新时间:2023-11-01 00:39:00 29 4
gpt4 key购买 nike

我的要求是通过过滤掉它的子域名来获取 URL 的域名。

我可以使用下面的代码获取主机名

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

因此 URL 中的 blog 是一个子域,abc 是一个域名,我希望通过排除它来仅知道/打印 abc子域部分。

在android中,有一个类InternetDomainName返回域名,我正在寻找iOS的类似解决方案

我尝试了几个答案,但没有重复,或者其中一些答案无效,或者这是一种解决方法。

Get the domain part of an URL string?

最佳答案

所以最后我找到了解决这个问题的更好的标准方法 -

Mozilla 志愿者维护公共(public)后缀列表和 there您可以找到相应语言的库列表。所以在列表中 Swift library也存在。在撰写此答案时 Swift library没有通过 CocoPods 添加它的条件,因此您必须将下载的项目直接添加到您的项目中。假定 Swift library 获取 TLD 名称的代码已添加到您的项目中。

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
}

将域解析器库添加为项目的子项目,因为该库的 pod 尚不可用

关于ios - 如何在 swift 4 中获取 URL 的顶级域名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51476379/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com