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
Get the domain part of an URL string?
提问by pmerino
I have an NSString with an URL, in this way:
我有一个带有 URL 的 NSString,以这种方式:
http://someurl.com/something
How would I get someurl.com
only?
I've already tried substringToIndex
with 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 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 index
method below and then pattern matching
to scrape everything after ":"
(并且没有“带有主机名的正斜杠”(//www.bbc)),一种对我有用的提取“主屏幕”的解决方案是通过using the index
下面的方法然后pattern matching
在之后刮掉所有内容":"
let index = absoluteString.index(absoluteString.startIndex, offsetBy: 5)
String(absoluteString[index...])
url.host
or absoluteURL.host
is nil
in this scenario
url.host
或者absoluteURL.host
是nil
在这种情况下