【问题标题】:NSString won't convert to NSURL (NSURL is null)NSString 不会转换为 NSURL(NSURL 为空)
【发布时间】:2012-04-05 11:08:45
【问题描述】:

我正在尝试将 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 包含斜杠 / 和破折号 -。我做错了什么?谢谢。

【问题讨论】:

    标签: iphone objective-c ios ipad nsurl


    【解决方案1】:

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

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

    然后用这样的文件路径创建你的 url。

    NSURL *url = [NSURL fileURLWithPath:filePath];
    

    【讨论】:

    • 你甚至可以更进一步,使用-[NSBundle URLForResource:withExtension:],它会直接给你一个file:// URL。
    【解决方案2】:

    问题是,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]]];
    

    【讨论】:

      猜你喜欢
      • 2016-07-28
      • 2011-12-26
      • 2012-02-10
      • 1970-01-01
      • 2016-04-07
      • 1970-01-01
      • 2014-10-25
      • 1970-01-01
      • 2012-11-10
      相关资源
      最近更新 更多