ios 是否获取URL字符串的域部分?

kpbpu008  于 2022-11-19  发布在  iOS
关注(0)|答案(7)|浏览(183)

我有一个带有URL的NSString,如下所示:

http://someurl.com/something

我怎么会只得到someurl.com呢?我已经试过substringToIndex了,但没有成功:(
提前感谢:)

d7v8vwbk

d7v8vwbk1#

目标-C

NSString* urlString = @"http://someurl.com/something";
NSURL* url = [NSURL URLWithString:urlString];
NSString* domain = [url host];

雨燕2

var urlString = "http://someurl.com/something"
var url = NSURL(string: urlString)
var domain = url?.host

雨燕3+

var urlString = "http://someurl.com/something"
var url = URL(string: urlString)
var domain = url?.host
pkwftd7m

pkwftd7m2#

用途

[[NSURL URLWithString:@"http://someurl.com/something"] host]
mkshixfv

mkshixfv3#

雨燕4.2

我写了扩展的URL采取SLD。似乎,有n

extension URL {
    /// second-level domain [SLD]
    ///
    /// i.e. `msk.ru, spb.ru`
    var SLD: String? {
        return host?.components(separatedBy: ".").suffix(2).joined(separator: ".")
    }
}
jq6vz3qz

jq6vz3qz4#

"雨燕5"
string的扩展名,它给出了域名,同时还删除了“www”。

extension String {
func StripURLMakeAttractive(_ url: String) -> String {
        
    let url = URL(string: url)
    guard let domain = url?.host else {return "error"}
    var modifiedDomain: String = ""
    
    var checkWWW: String = ""
    let checkIndexes = [0,1,2,3]

    for (index,char) in domain.enumerated() {
        if checkIndexes.contains(index){
            checkWWW.append(char)
        }
        if index > 3 && checkWWW.lowercased() == "www."  {
            modifiedDomain.append(char)
        }
    }
    
    if checkWWW.lowercased() == "www."{
        return modifiedDomain
    }
    else {
        return domain
    }
    
}

}

gpnt7bae

gpnt7bae5#

您应该查看NSURL类的host()方法。

31moq8wy

31moq8wy6#

雨燕5.5

extension String {
    var onlyHost: String? {
        let url = URL(string: self)
        return url?.host
    }
}
wpx232ag

wpx232ag7#

雨燕4

如果您使用自定义url方案,则表示用于深度链接,例如:

myapp:homescreen

(and我没有“正斜杠与主机名”(//www.bbc)),一个解决方案,为我工作,以提取“主屏幕”是通过下面的using the index方法,然后pattern matching刮取":"后的一切

let index = absoluteString.index(absoluteString.startIndex, offsetBy: 5)
String(absoluteString[index...])

url.hostabsoluteURL.host在此方案中为**nil**

相关问题