Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSString won't convert to NSURL (NSURL is null)

I'm trying to convert a NSString (a path to a file in the documents directory) to a NSURL, but the NSURL is always null. Here is my code:

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

And here is the log:

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)

I think part of the problem might be that the NSString contains slashes / and dashes -. What am I doing incorrectly? Thanks.

like image 477
Jack Humphries Avatar asked Dec 17 '22 02:12

Jack Humphries


2 Answers

Why don't you create your file path in this way which is.

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

And then create your url with file path like this.

NSURL *url = [NSURL fileURLWithPath:filePath];
like image 168
Serdar Dogruyol Avatar answered Dec 26 '22 21:12

Serdar Dogruyol


The thing is, appDelegate.pdfString isn't a valid URL, it's a path. A file URL looks like:

file://host/path

or for the local host:

file:///path

So you actually want:

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

...except your path has spaces, which need to be URL encoded, so you actually want:

NSURL *urlToPDF = [NSURL URLWithString:[NSString stringWithFormat:@"file:///%@", [appDelegate.pdfString stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]]];
like image 32
Kristian Glass Avatar answered Dec 26 '22 19:12

Kristian Glass