0

I've got the following function:

- (void)loadPdfFromPath:(NSString*)path
{   
    NSURL *pathUrl = [NSURL URLWithString:path];

    _pdfDocument = CGPDFDocumentCreateWithURL((CFURLRef)pathUrl);
}

Which from the documentation I'm lead to believe will work because you can case from an NSURL* to a CFURLRef via Toll-Free Bridging. However, this function fails, and I get the following output in the log:

CFURLCreateDataAndPropertiesFromResource: error code -15.

NB: -15 = kCFURLImproperArgumentsError

However, if I create an actual CFURLRef, it works absolutely fine:

- (void)loadPdfFromPath:(NSString*)path
{
    CGPDFDocumentRelease(_pdfDocument);

    CFStringRef cgPath = CFStringCreateWithCString(NULL, [path UTF8String], kCFStringEncodingUTF8);

    CFURLRef url = CFURLCreateWithFileSystemPath(NULL, cgPath, kCFURLPOSIXPathStyle, 0);

    _pdfDocument = CGPDFDocumentCreateWithURL(url);

    CFRelease(url);
    CFRelease(cgPath)
}

What am I missing? I'm happy to keep the second function in my code, but I'd rather know why the first one is failing.

Mark Ingram
  • 71,849
  • 51
  • 176
  • 230

2 Answers2

5

To convert a file system path to a URL, use

NSURL *pathUrl = [NSURL fileURLWithPath:path];

URLWithString expects a RFC 2396 conforming URL string like "http://..." or "file:///...", including the "scheme" etc.

Added: Actually NSURL *pathUrl = [NSURL URLWithString:path]; returns a valid object, so it seems to work, but reading from this URL (e.g. dataWithContentsOfURL) fails.

Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
2

You need the convert NSString to CFStringRef then call CFURLCreateWithFileSystemPath;

CFStringRef aCFString = (__bridge CFStringRef)path;
CFURLRef url = CFURLCreateWithFileSystemPath (NULL, aCFString,  kCFURLPOSIXPathStyle, 0);
NSLog(@"NSURL %@",url);
codezero
  • 99
  • 1
  • 7