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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6162522/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 20:07:53  来源:igfitidea点击:

Get the domain part of an URL string?

cocoa-touchiosios4

提问by pmerino

I have an NSString with an URL, in this way:

我有一个带有 URL 的 NSString,以这种方式:

http://someurl.com/something

How would I get someurl.comonly? I've already tried substringToIndexwith no luck :(

我怎么会someurl.com只有?我已经试过了substringToIndex,但没有运气:(

Thanks in advance :)

提前致谢 :)

回答by Stephen Darlington

Objective-C

目标-C

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

Swift 2

斯威夫特 2

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

Swift 3+

斯威夫特 3+

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

回答by Deepak Danduprolu

Use

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

回答by Alexey Lysenko

Swift 4.2

斯威夫特 4.2

I wrote extension for URL to take SLD. Seems, there is n

我为 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: ".")
    }
}

回答by Brian Lyttle

You should look at the host()method of the NSURLclass.

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

回答by Naishta

Swift 4

斯威夫特 4

And if you are using Custom url schemessay for deeplinking, for eg:

如果您使用自定义 url 方案进行深层链接,例如:

myapp:homescreen

(and don't have the "forward slashes with host name" (//www.bbc)), one solution that worked for me to extract "homescreen" is by using the indexmethod below and then pattern matchingto scrape everything after ":"

(并且没有“带有主机名的正斜杠”(//www.bbc)),一种对我有用的提取“主屏幕”的解决方案是通过using the index下面的方法然后pattern matching在之后刮掉所有内容":"

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

url.hostor absoluteURL.hostis nilin this scenario

url.host或者absoluteURL.hostnil在这种情况下