Jack Humphries
Jack Humphries

Reputation: 13267

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.

Upvotes: 4

Views: 1443

Answers (2)

Kristian Glass
Kristian Glass

Reputation: 38540

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]]];

Upvotes: 6

Serdar Dogruyol
Serdar Dogruyol

Reputation: 5157

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];

Upvotes: 6

Related Questions