删除NSURL的最后部分:iOS
我想删除只是URL的最后一部分,它的FTP URL。删除NSURL的最后部分:iOS
假设,我有一个URL:>ftp://ftp.abc.com/public_html/somefolder/。删除最后一部分后,我应该把它作为:ftp://ftp.abc.com/public_html/。
我试过使用stringByDeletingLastPathComponenet
和URLByDeletingLastPathComponent
,但他们没有正确删除最后一部分。他们改变了整个网址的外观。
例如,使用上述方法后,这里是URL格式,我得到了ftp:/ftp.abc.com/public_html/。它会删除“ftp://”中的一个“/”,这会导致我的程序崩溃。
如何在不干扰URL的其余部分的情况下删除最后一部分?
UPDATE:
NSURL * stringUrl = [NSURL URLWithString:string];
NSURL * urlByRemovingLastComponent = [stringUrl URLByDeletingLastPathComponent];
NSLog(@"%@", urlByRemovingLastComponent);
使用上面的代码中,我得到的输出: - FTP:/ftp.abc.com/public_html/
现在尝试
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/
这确实有效,但URL可以是任何内容,如果是 ftp://ftp.abc.com/public_html/somefolder/someOtherFolder/? 此方法不会产生正确的结果。 – Shailesh 2013-05-11 05:44:13
ohhh ..我认为url是固定的。只是等待 – 2013-05-11 05:45:38
看到我编辑的答案 – 2013-05-11 06:00:41
嗯。在上面的输入中,URLByDeletingLastPathComponent完美地工作。
NSURL *url = [NSURL URLWithString:@"ftp://ftp.abc.com/public_html/somefolder/"];
NSLog(@"%@", [url URLByDeletingLastPathComponent]);
回报
ftp://ftp.abc.com/public_html/
你有被不当产生的结果一些示例代码?
最大
的如何提取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
'-stringByDeletingLastPathComponent'确实会凝结任何双斜杠。虽然它的文档明确表明它只用于路径,而不是URL! – 2013-05-11 08:43:07
'-URLByDeletingLastPathComponent'虽然正常工作。我只能看到上面的代码示例输出'ftp:/ ftp.abc.com/public_html /',如果输入的格式类似于'ftp:/ ftp.abc.com/public_html/somefolder/ – 2013-05-11 08:44:04
快速跟进:在OS X 10.6(推测是iOS 4)上出现'-URLByDeletingLastPathComponent'错误处理路径部分中的双斜线。试图删除这样的组件导致'../'被附加代替 – 2014-01-25 20:04:00