簡體   English   中英

如何從包含空格的字符串創建NSURL?

[英]How do you create an NSURL from a string containing spaces?

此代碼的結果是url為null

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];

您的問題不是從包含空格的字符串創建URL,而是從包含空格的路徑字符串創建URL。

對於路徑,不應使用URLWithString Mac OS X和iOS包括便捷功能,用於為文件路徑構建NSURL,以便自動處理此問題。 請改用其中一個。

Apple的[NSURL fileURLWithPath: path]文檔說:

此方法假定路徑是以斜杠結尾的目錄。 如果path不以斜杠結束,則該方法檢查文件系統以確定路徑是文件還是目錄。 如果path存在於文件系統中並且是目錄,則該方法會附加一個尾部斜杠。 如果文件系統中不存在path ,則該方法假定它表示文件而不附加尾部斜杠。

作為替代方案,請考慮使用fileURLWithPath:isDirectory: ,它允許您顯式指定返回的NSURL對象是表示文件還是目錄。

此外,您應該使用NSSearchPathForDirectoriesInDomains來查找Application Support目錄。

把這一切放在一起,你最終得到這樣的東西:

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

資源:

您實際上需要添加百分比轉義,而不是刪除它們:

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

Swift 2.0版本:

let encodedPath = path?.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())!

首先,如果您實際上正在嘗試獲取應用程序的應用程序支持目錄,請使用適當的作業方法(在本例中為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)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM