Get the domain part of an URL string?

后端 未结 5 1946
一整个雨季
一整个雨季 2020-12-24 13:16

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

http://someurl.com/something

How would I get someurl.com only? I\'ve already trie

相关标签:
5条回答
  • 2020-12-24 13:32

    Use

    [[NSURL URLWithString:@"http://someurl.com/something"] host]
    
    0 讨论(0)
  • 2020-12-24 13:32

    Swift 4

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

    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 ":"

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

    url.host or absoluteURL.host is nil in this scenario

    0 讨论(0)
  • 2020-12-24 13:36

    Swift 4.2

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

    extension URL {
        /// second-level domain [SLD]
        ///
        /// i.e. `msk.ru, spb.ru`
        var SLD: String? {
            return host?.components(separatedBy: ".").suffix(2).joined(separator: ".")
        }
    }
    
    0 讨论(0)
  • 2020-12-24 13:41

    You should look at the host() method of the NSURL class.

    0 讨论(0)
  • 2020-12-24 13:48

    Objective-C

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

    Swift 2

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

    Swift 3+

    var urlString = "http://someurl.com/something"
    var url = URL(string: urlString)
    var domain = url?.host
    
    0 讨论(0)
提交回复
热议问题