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.
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];
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]]];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With