2013-05-11 71 views
11

我想刪除只是URL的最後一部分,它的FTP URL。刪除NSURL的最後部分:iOS

假設,我有一個URL:>ftp://ftp.abc.com/public_html/somefolder/。刪除最後一部分後,我應該把它作爲:ftp://ftp.abc.com/public_html/

我試過使用stringByDeletingLastPathComponenetURLByDeletingLastPathComponent,但他們沒有正確刪除最後一部分。他們改變了整個網址的外觀。

例如,使用上述方法後,這裏是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/

+1

'-stringByDeletingLastPathComponent'確實會凝結任何雙斜槓。雖然它的文檔明確表明它只用於路徑,而不是URL! – 2013-05-11 08:43:07

+1

'-URLByDeletingLastPathComponent'雖然正常工作。我只能看到上面的代碼示例輸出'ftp:/ ftp.abc.com/public_html /',如果輸入的格式類似於'ftp:/ ftp.abc.com/public_html/somefolder/ – 2013-05-11 08:44:04

+1

快速跟進:在OS X 10.6(推測是iOS 4)上出現'-URLByDeletingLastPathComponent'錯誤處理路徑部分中的雙斜線。試圖刪除這樣的組件導致'../'被附加代替 – 2014-01-25 20:04:00

回答

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/ 
+0

這確實有效,但URL可以是任何內容,如果是 ftp://ftp.abc.com/public_html/somefolder/someOtherFolder/? 此方法不會產生正確的結果。 – Shailesh 2013-05-11 05:44:13

+0

ohhh ..我認爲url是固定的。只是等待 – 2013-05-11 05:45:38

+0

看到我編輯的答案 – 2013-05-11 06:00:41

17

嗯。在上面的輸入中,URLByDeletingLastPathComponent完美地工作。

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

回報

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

你有被不當產生的結果一些示例代碼?

最大

+1

@Max:請檢查我的問題更新。 – Shailesh 2013-05-11 05:36:12

+1

不幸的是,我無法複製你遇到的錯誤。字符串輸入可能是畸形的嗎? – mxweas 2013-05-11 05:38:07

+1

@Max:我不確定但是,我從TextFields提供輸入。 – Shailesh 2013-05-11 05:43:25

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