Search code examples
iphoneios6ftpnsstringnsurl

Remove last portion of the NSURL: iOS


I am trying to remove just the last part of the url, Its a FTP URL.

Suppose, I have a URL like: > ftp://ftp.abc.com/public_html/somefolder/. After removing the last portion I should have it as: ftp://ftp.abc.com/public_html/.

I have tried using stringByDeletingLastPathComponenet and URLByDeletingLastPathComponent, but they dont remove the last portion correctly. They change the entire looks of the url.

for instance, after using the above said methods, here is the URL format i get ftp:/ftp.abc.com/public_html/. It removes one "/" in "ftp://", which is crashing my program.

How is it possible to removve just the last part without disturbing the rest of the URL ?

UPDATE:

NSURL * stringUrl = [NSURL URLWithString:string];
NSURL * urlByRemovingLastComponent = [stringUrl URLByDeletingLastPathComponent];
NSLog(@"%@", urlByRemovingLastComponent);

Using above code, I get the output as :- ftp:/ftp.abc.com/public_html/


Solution

  • Now try

        NSString* filePath = @"ftp://ftp.abc.com/public_html/somefolder/.";
    
        NSArray* pathComponents = [filePath pathComponents];
        NSLog(@"\n\npath=%@",pathComponents);
        if ([pathComponents count] > 2) {
                NSArray* lastTwoArray = [pathComponents subarrayWithRange:NSMakeRange([pathComponents count]-2,2)];
                NSString* lastTwoPath = [NSString pathWithComponents:lastTwoArray];
                 NSLog(@"\n\nlastTwoArray=%@",lastTwoPath);
    
                NSArray *listItems = [filePath componentsSeparatedByString:lastTwoPath];
                NSLog(@"\n\nlist item 0=%@",[listItems objectAtIndex:0]);
    
         }
    
    
    output
    
    path=(
          "ftp:",
          "ftp.abc.com",
          "public_html",
          somefolder,
          "."
          )
    
    lastTwoArray =somefolder/.
    
    list item 0 =ftp://ftp.abc.com/public_html/