Получить корневой URL - NSString - PullRequest
1 голос
/ 18 февраля 2011

Я пытаюсь получить корневой URL-адрес строки NSString, содержащей URL-адрес.Например, если передан URL-адрес secure.twitter.com, я хочу получить twitter.com.Это работает в классе, который я сделал ниже.Однако он не работает для более длинных URL-адресов ...

Вот мой метод:

-

(NSString *)getRootDomain:(NSString *)domain
{
    NSString*output = [NSString stringWithString:domain];

    if ([output rangeOfString:@"www."].location != NSNotFound)
    {
    //if the www is still there, get rid of it
    output = [domain stringByReplacingOccurrencesOfString:@"www." withString:@""];
    }

    if ([output rangeOfString:@"http://"].location != NSNotFound)
    {
    //if the http is still there, get rid of it
    output = [domain stringByReplacingOccurrencesOfString:@"http://" withString:@""];
    }

    if ([output rangeOfString:@"https://"].location != NSNotFound)
    {
    //if the https is still there, get rid of it
    output = [domain stringByReplacingOccurrencesOfString:@"https://" withString:@""];
    }

    NSLog(@"New: %@",output);

    NSArray*components = [output componentsSeparatedByString:@"."];

    if ([components count] == 2) //dandy, this is an easy one
    {
        return output;
    }

    if ([components count] == 3) //secure.paypal.com
    {
        NSString*newurl = [NSString stringWithFormat:@"%@.%@",[components objectAtIndex:1],[components objectAtIndex:2]];

        return newurl;
    }

    if ([components count] == 4) //secure.paypal.co.uk
    {
        NSString*newurl = [NSString stringWithFormat:@"%@.%@.%@",[components objectAtIndex:1],[components objectAtIndex:2],[components objectAtIndex:3]];

        return newurl;
    }


    //Path Components will return the root url in its array in object 0 (usually)

    NSArray*path_components = [output pathComponents];  

    return [path_components objectAtIndex:0];
}

Как я могу заставить эту работу работать для любого URL-адреса?*

Ответы [ 6 ]

4 голосов
/ 18 февраля 2011

Вы можете рассмотреть возможность использования NSURL и NSString для этого, например:

(NSString *)getRootDomain:(NSString *)domain
{
    // Return nil if none found.
    NSString * rootDomain = nil;

    // Convert the string to an NSURL to take advantage of NSURL's parsing abilities.
    NSURL * url = [NSURL URLWithString:domain];

    // Get the host, e.g. "secure.twitter.com"
    NSString * host = [url host];

    // Separate the host into its constituent components, e.g. [@"secure", @"twitter", @"com"]
    NSArray * hostComponents = [host componentsSeparatedByString:@"."];
    if ([hostComponents count] >=2) {
        // Create a string out of the last two components in the host name, e.g. @"twitter" and @"com"
        rootDomain = [NSString stringWithFormat:@"%@.%@", [hostComponents objectAtIndex:([hostComponents count] - 2)], [hostComponents objectAtIndex:([hostComponents count] - 1)]];
    }

    return rootDomain;
}
0 голосов
/ 14 марта 2017
[[NSURL URLWithString:@"http://someurl.com/something"] host]

вывод: someurl.com

0 голосов
/ 11 января 2015

Вам необходимо проверить суффиксы.

Пример:

#import "NSURL+RootDomain.h"

@implementation NSURL(RootDomain)

- (NSString *)rootDomain {
    NSArray *hostComponents = [self.host componentsSeparatedByString:@"."];
    NSArray *suffixs = [NSArray arrayWithObjects:@"net", @"com", @"gov", @"org", @"edu", @"com.cn", @"me", nil];

    if ([hostComponents count] >= 2) {
        if ([hostComponents[hostComponents.count - 2] isEqualToString:@"cn"]) {
            if ([suffixs containsObject:[hostComponents lastObject]]) {
                return [NSString stringWithFormat:@"%@.%@.%@", hostComponents[hostComponents.count - 3], hostComponents[hostComponents.count - 2], hostComponents.lastObject];
            } else {
                return [NSString stringWithFormat:@"%@.%@", hostComponents[hostComponents.count - 2], hostComponents.lastObject];
            }
        } else {
            return [NSString stringWithFormat:@"%@.%@", hostComponents[hostComponents.count - 2], hostComponents.lastObject];
        }
    }

    return self.host;
}
0 голосов
/ 16 августа 2012

Первая точка в URL-адресе всегда является частью доменного имени, мы можем использовать это для создания этого простого, но очень эффективного метода.(и он работает с поддоменами и TLD с несколькими точками, как co.uk)

-(NSString*)domainFromUrl:(NSString*)url
{
    NSArray *first = [url componentsSeparatedByString:@"/"];
    for (NSString *part in first) {
        if ([part rangeOfString:@"."].location != NSNotFound){
            return part;
        }
    }
    return nil;
}
NSLog(@"%@",[self domainFromUrl:@"http://foobar1.com/foo/"]);
NSLog(@"%@",[self domainFromUrl:@"http://foobar2.com/foo/bar.jpg"]);
NSLog(@"%@",[self domainFromUrl:@"http://foobar3.com/"]);
NSLog(@"%@",[self domainFromUrl:@"http://foobar4.com"]);
NSLog(@"%@",[self domainFromUrl:@"foobar5.com"]);




2012-08-15 23:25:14.769 SandBox[9885:303] foobar1.com
2012-08-15 23:25:14.772 SandBox[9885:303] foobar2.com
2012-08-15 23:25:14.772 SandBox[9885:303] foobar3.com
2012-08-15 23:25:14.773 SandBox[9885:303] foobar4.com
2012-08-15 23:25:14.773 SandBox[9885:303] foobar5.com
0 голосов
/ 11 июня 2012

Чтобы получить части URL, вот идеальный ответ . Однако вы хотите разделить хост-часть URL. С NSURL вы можете получить хост так: url.host

От хозяина нет способа узнать, какая важная часть. Может быть хост с именем secure.twitter.com и еще один с именем twitter.host1.com.

Если вы получили пользовательскую спецификацию, например, удалите «secure». если это префикс хоста, реализуйте его. Но если вы пытаетесь найти универсальное решение, я бы лучше сохранил всю строку хоста.

0 голосов
/ 18 февраля 2011
NSArray *array = [[newURL host] componentsSeparatedByString: @"."];
NSLog(@"%@", [NSString stringWithFormat:@"%@.%@", [array objectAtIndex:[array count]-2], [array objectAtIndex:[array count]-1]]);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...