删除NSURL的最后一部分:iOS

问题描述 投票:12回答:3

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

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

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

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

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

更新:

stringByDeletingLastPathComponenet

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

iphone ios6 ftp nsstring nsurl
3个回答
2
投票

现在试试

URLByDeletingLastPathComponent

18
投票

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

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

回报

    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/

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

马克斯


1
投票

如何提取NSURL的最后部分的示例。在这种情况下,文件的位置。 Sqlite核心数据

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

此代码返回文件CoreAPI.sqlite的名称

© www.soinside.com 2019 - 2024. All rights reserved.