NSString将不会转换为NSURL(NSURL为空)
问题描述:
我试图将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的包含斜杠/和破折号 - 。我做错了什么?谢谢。
答
为什么不用这种方式创建文件路径。
NSString *filePath = [[NSBundle mainBundle]pathForResource:@"pdfName" ofType:@"pdf"];
然后用这样的文件路径创建你的url。
NSURL *url = [NSURL fileURLWithPath:filePath];
答
事情是,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]]];
很高兴听到:) – 2012-03-20 22:40:49
你甚至可以更进一步,并使用' - [NSBundle URLForResource:withExtension:]',它会直接给你一个file:// URL。 – 2012-03-20 22:41:48