3

此代码的结果是 url 为空

NSString* home = [NSHomeDirectory() stringByAppendingPathComponent:@"/Library/Application Support/"];
NSURL *url = [NSURL URLWithString:home];

这是这样的:

NSString* home = [NSHomeDirectory() stringByAppendingPathComponent:@"/Library/Application Support/"];
home = [home stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:home];
4

4 回答 4

11

您的问题不是关于从包含空格的字符串创建 URL ,而是从包含空格的路径字符串创建 URL 。

对于路径,您不应使用URLWithString. Mac OS X 和 iOS 包含用于为文件路径构建 NSURL 的便利功能,这些功能会自动为您处理这些以及更多。请改用其中之一。

苹果的文档[NSURL fileURLWithPath: path]说:

如果路径以斜杠结尾,则此方法假定路径是目录。如果路径不以斜线结尾,则该方法检查文件系统以确定路径是文件还是目录。如果路径存在于文件系统中并且是一个目录,则该方法会附加一个尾部斜杠。如果文件系统中不存在路径,则该方法假定它表示文件并且不附加尾部斜杠。

作为替代方案,请考虑使用fileURLWithPath:isDirectory:,它允许您明确指定返回的NSURL对象是代表文件还是目录。

此外,您应该使用它NSSearchPathForDirectoriesInDomains来查找应用程序支持目录。

把这一切放在一起,你最终会得到这样的东西:

NSArray *paths = NSSearchPathForDirectoriesInDomains(
                     NSApplicationSupportDirectory, NSUserDomainMask, YES);
NSString *applicationSupportDirectory = [paths objectAtIndex:0];
NSURL *url = [NSURL fileURLWithPath: applicationSupportDirectory isDirectory: YES];

来源:

于 2012-07-18T19:52:29.807 回答
4

您实际上需要添加百分比转义,而不是删除它们:

NSString* home = [NSHomeDirectory() stringByAppendingPathComponent:@"/Library/Application Support/"];
    NSURL *url = [NSURL URLWithString:[home stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    NSLog(@"%@", url);

打印:

2012-07-18 13:44:54.738 Test[1456:907] /var/mobile/Applications/FF6E6881-1D1B-4B74-88DF-06A2B62CCFE6/Library/Application%20Support
于 2012-07-18T19:45:30.630 回答
4

斯威夫特 2.0 版本:

let encodedPath = path?.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())!
于 2016-04-10T03:04:30.283 回答
1

首先,如果您实际上是在尝试获取应用程序的应用程序支持目录,请使用适当的方法(在本例中为 on NSFileManager)并直接处理 URL:

NSURL* appSupport = [[NSFileManager defaultManager] URLForDirectory: NSApplicationSupportDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:YES error:NULL];

如果你真的想建立一个路径,那么使用适当的初始化程序,在这种情况下,告诉 URL 它是一个文件路径 URL,这样它就会自然地处理空格,你可能可以建立 URL 路径(这个例子更多就像你上面的代码):

NSString* home = [NSHomeDirectory() stringByAppendingPathComponent:@"/Library/Application Support/"];
// Here, use the appropriate initializer for NSURL
NSURL *url = [NSURL fileURLWithPath:home];

现在,URL 将被正确地进行百分比编码,您不会有任何问题(返回时它不会为 nil)。

于 2012-07-18T20:08:46.823 回答