删除NSURL的最后一部分:iOS

Sha*_*esh 12 iphone ftp nsurl nsstring ios6

我试图删除网址的最后一部分,它是一个FTP URL.

假设我有一个URL:> ftp://ftp.abc.com/public_html/somefolder/.删除最后一部分后,我应该将其作为:ftp://ftp.abc.com/public_html/.

我尝试使用stringByDeletingLastPathComponenetURLByDeletingLastPathComponent,但他们没有正确删除最后一部分.它们会改变网址的整体外观.

例如,在使用上述方法之后,这里是我得到的URL格式:ftp:/ftp.abc.com/public_html/.它会删除"ftp://"中的一个"/",这会导致我的程序崩溃.

如何在不干扰URL其余部分的情况下删除最后一部分?

更新:

NSURL * stringUrl = [NSURL URLWithString:string];
NSURL * urlByRemovingLastComponent = [stringUrl URLByDeletingLastPathComponent];
NSLog(@"%@", urlByRemovingLastComponent);
Run Code Online (Sandbox Code Playgroud)

使用上面的代码,我得到的输出为: - ftp:/ftp.abc.com/public_html/

小智 18

嗯.鉴于上述输入,URLByDeletingLastPathComponent完美地工作.

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

回报

ftp://ftp.abc.com/public_html/
Run Code Online (Sandbox Code Playgroud)

您是否有一些示例代码产生不正确的结果?

马克斯


SAM*_*HOD 2

现在尝试

    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/
Run Code Online (Sandbox Code Playgroud)