NSString不会转换为NSURL(NSURL为null)

Jac*_*ies 4 iphone objective-c nsurl ipad ios

我正在尝试将NSString(文档目录中的文件的路径)转换为NSURL,但NSURL始终为null.这是我的代码:

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

这是日志:

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)
Run Code Online (Sandbox Code Playgroud)

我认为问题的一部分可能是NSString包含斜杠/和破折号 - .我做错了什么?谢谢.

Ser*_*yol 6

为什么不以这种方式创建文件路径.

NSString *filePath = [[NSBundle mainBundle]pathForResource:@"pdfName" ofType:@"pdf"];
Run Code Online (Sandbox Code Playgroud)

然后使用这样的文件路径创建您的URL.

NSURL *url = [NSURL fileURLWithPath:filePath];
Run Code Online (Sandbox Code Playgroud)

  • 您甚至可以更进一步使用` - [NSBundle URLForResource:withExtension:]`,它将直接为您提供file:// URL. (2认同)

Kri*_*ass 6

问题是,appDelegate.pdfString它不是有效的URL,而是一条路径.一个文件的URL是这样的:

file://host/path
Run Code Online (Sandbox Code Playgroud)

或者为当地主人:

file:///path
Run Code Online (Sandbox Code Playgroud)

所以你真的想要:

NSURL *urlToPDF = [NSURL URLWithString:[NSString stringWithFormat:@"file:///%@", appDelegate.pdfString]];
Run Code Online (Sandbox Code Playgroud)

...除了你的路径有空格,需要进行URL编码,所以你真的想要:

NSURL *urlToPDF = [NSURL URLWithString:[NSString stringWithFormat:@"file:///%@", [appDelegate.pdfString stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]]];
Run Code Online (Sandbox Code Playgroud)