2012-03-20 46 views
4

我試圖將NSString(文檔目錄中的文件的路徑)轉換爲NSURL,但NSURL始終爲空。這裏是我的代碼:NSString將不會轉換爲NSURL(NSURL爲空)

NSURL *urlToPDF = [NSURL URLWithString:appDelegate.pdfString]; 
NSLog(@"AD: %@", appDelegate.pdfString); 
NSLog(@"PDF: %@", urlToPDF); 
pdf = CGPDFDocumentCreateWithURL((CFURLRef)urlToPDF); 

而且這裏是日誌:

2012-03-20 18:31:49.074 The Record[1496:15503] AD: /Users/John/Library/Application Support/iPhone Simulator/5.1/Applications/E1F20602-0658-464D-8DDC-52A842CD8146/Documents/issues/3.1.12/March 1, 2012.pdf 
2012-03-20 18:31:49.074 The Record[1496:15503] PDF: (null) 

我認爲問題的一部分,可能是NSString的包含斜槓/和破折號 - 。我做錯了什麼?謝謝。

回答

6

爲什麼不用這種方式創建文件路徑。

NSString *filePath = [[NSBundle mainBundle]pathForResource:@"pdfName" ofType:@"pdf"]; 

然後用這樣的文件路徑創建你的url。

NSURL *url = [NSURL fileURLWithPath:filePath]; 
+0

很高興聽到:) – 2012-03-20 22:40:49

+2

你甚至可以更進一步,並使用' - [NSBundle URLForResource:withExtension:]',它會直接給你一個file:// URL。 – 2012-03-20 22:41:48

6

事情是,appDelegate.pdfString不是一個有效的URL,它是一個路徑。一個file URL樣子:

file://host/path 

或本地主機:

file:///path 

所以你真的想:

NSURL *urlToPDF = [NSURL URLWithString:[NSString stringWithFormat:@"file:///%@", appDelegate.pdfString]]; 

...除了你的路徑中有空格,它必須是URL編碼,所以你其實想要:

NSURL *urlToPDF = [NSURL URLWithString:[NSString stringWithFormat:@"file:///%@", [appDelegate.pdfString stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]]];