NSString will not convert to NSURL (NSURL - null)

I am trying to convert NSString (the file path in the document directory) to NSURL, but 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 magazine:

 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 NSString contains slashes / and dashes -. What am I doing wrong? Thanks.

+4
source share
2 answers

Why don't you create your file path in the way that it is.

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

And then create your url with this path.

 NSURL *url = [NSURL fileURLWithPath:filePath]; 
+6
source

The fact is that appDelegate.pdfString not a valid URL, this is the way to go. A file url is as follows:

 file://host/path 

or for localhost:

 file:///path 

So you really want:

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

... besides your path, there are spaces that should be encoded in the URL, so you really want to:

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

Source: https://habr.com/ru/post/1402559/


All Articles