Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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/

like image 994
Shailesh Avatar asked May 11 '13 05:05

Shailesh


2 Answers

Hmm. URLByDeletingLastPathComponent works perfectly given the above input.

NSURL *url = [NSURL URLWithString:@"ftp://ftp.abc.com/public_html/somefolder/"];
NSLog(@"%@", [url URLByDeletingLastPathComponent]);

returns

ftp://ftp.abc.com/public_html/

Do you have some sample code that is yielding improper results?

Max

like image 169
mxweas Avatar answered Oct 12 '22 10:10

mxweas


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/
like image 31
SAMIR RATHOD Avatar answered Oct 12 '22 10:10

SAMIR RATHOD