iOS: parse a URL into segments

前端 未结 4 455
闹比i
闹比i 2020-12-02 08:41

What\'s an efficient way to take an NSURL object such as the following:

foo://name/12345 

and break it up into one string and one unsigned

4条回答
  •  萌比男神i
    2020-12-02 09:28

    Thanks to Nick for pointing me in the right direction.

    I wanted to compare file urls but was having problems with extra slashes making isEqualString useless. You can use my example below for comparing two urls by first de-constructing them and then comparing the parts against each other.

    - (BOOL) isURLMatch:(NSString*) url1 url2:(NSString*) url2
    {
        NSURL *u1 = [NSURL URLWithString:url1];
        NSURL *u2 = [NSURL URLWithString:url2];
    
        if (![[u1 scheme] isEqualToString:[u2 scheme]]) return NO;
        if (![[u1 host] isEqualToString:[u2 host]]) return NO;
        if (![[url1 pathComponents] isEqualToArray:[url2 pathComponents]]) return NO;
    
        //check some properties if not nil as isEqualSting fails when comparing them
        if ([u1 port] && [u2 port])
        {
            if (![[u1 port] isEqualToNumber:[u2 port]]) return NO;
        }
    
        if ([u1 query] && [u2 query])
        {
            if (![[u1 query] isEqualToString:[u2 query]]) return NO;
        }
        return YES;
    }  
    

提交回复
热议问题