Iphone 删除NSURL:iOS的最后一部分
我正在尝试删除url的最后一部分,它是一个FTP url 假设我有一个URL,如:>。删除最后一部分后,我应该将其作为: 我已尝试使用Iphone 删除NSURL:iOS的最后一部分,iphone,ios6,ftp,nsstring,nsurl,Iphone,Ios6,Ftp,Nsstring,Nsurl,我正在尝试删除url的最后一部分,它是一个FTP url 假设我有一个URL,如:>。删除最后一部分后,我应该将其作为: 我已尝试使用stringbydeletinglastpathcomponnenet和URLByDeletingLastPathComponent,但它们无法正确删除最后一部分。它们会改变url的整个外观 例如,在使用上述方法之后,下面是我得到的ftp:/ftp.abc.com/public\u html/的URL格式。它删除了“ftp://”中的一个“/”,这会使我的程序崩溃
stringbydeletinglastpathcomponnenet
和URLByDeletingLastPathComponent
,但它们无法正确删除最后一部分。它们会改变url的整个外观
例如,在使用上述方法之后,下面是我得到的ftp:/ftp.abc.com/public\u html/的URL格式。它删除了“ftp://”中的一个“/”,这会使我的程序崩溃
如何在不干扰URL其余部分的情况下删除最后一部分
更新:
NSURL * stringUrl = [NSURL URLWithString:string];
NSURL * urlByRemovingLastComponent = [stringUrl URLByDeletingLastPathComponent];
NSLog(@"%@", urlByRemovingLastComponent);
使用上面的代码,我得到的输出是:-ftp:/ftp.abc.com/public_html/Hmm.URLByDeletingLastPathComponent在提供上述输入的情况下工作得非常好
NSURL *url = [NSURL URLWithString:@"ftp://ftp.abc.com/public_html/somefolder/"];
NSLog(@"%@", [url URLByDeletingLastPathComponent]);
返回
ftp://ftp.abc.com/public_html/
您是否有一些示例代码产生了不正确的结果
Max现在试试
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/
如何提取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的名称@Max:请检查我问题中的更新。不幸的是,我无法复制您遇到的错误。字符串输入是否有可能格式不正确?@Max:我不确定,但我提供的是来自TextFields的输入。当您记录(@“%@”,字符串)时会发生什么情况;就在尝试删除最后一个路径组件之前?它确实提供了正确的URL格式。这是我通过TextField输入的字符串这确实有效,但是URL可以是任何东西,如果是呢?这种方法不会产生正确的结果。。我认为url是固定的。等等,谢谢你,萨米尔。虽然你的回答不符合我的问题,但我必须找到其他解决办法。但是,还是。。我将您的解决方案用于其他目的。
-stringByDeletingLastPathComponent
确实会压缩任何双斜杠。它的文档明确指出它只用于路径,而不是URL<代码>-URLByDeletingLastPathComponent可以正常工作。我能看到的上述代码示例输出ftp:/ftp.abc.com/public_html/
的唯一情况是,输入的格式类似于ftp:/ftp.abc.com/public_html/somefolder/
Quick followup:在OS X 10.6(大概是iOS 4)上出现-URLByDeletingLastPathComponent
错误处理路径部分中的双斜杠。尝试删除这样一个组件会导致添加。/
,而不是随机思考:文本字段中的输入URL是否可能实际包含一个尾随的换行符?事实证明,在OSX10.9和IOS7之前,最后一个字符可能是无效的。我想这可能会破坏路径编辑逻辑