删除NSURL的最后一部分:iOS

时间:2013-05-11 05:20:39

标签: iphone ios6 ftp nsstring nsurl

我正在尝试删除网址的最后一部分,它是一个FTP网址。

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

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

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

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

更新

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

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

3 个答案:

答案 0 :(得分:18)

嗯。鉴于上述输入,URLByDeletingLastPathComponent可以正常工作。

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

返回

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

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

最高

答案 1 :(得分: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/

答案 2 :(得分:1)

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

NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"CoreAPI.sqlite"];

NSString *localPath = [storeURL absoluteString];

NSArray* pathComponents = [localPath pathComponents];

NSLog(@"%@",[pathComponents objectAtIndex:6]);

NSString * nombre = [NSString stringWithFormat:@"%@", [pathComponents objectAtIndex:6]];

此代码返回文件CoreAPI.sqlite

的名称