CGPDFDocumentCreateWithURL fails (Toll-Free bridging of NSURL to CFURLRef)

梦想的初衷 提交于 2019-12-25 04:54:12

问题


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.


回答1:


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.




回答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);


来源:https://stackoverflow.com/questions/15849081/cgpdfdocumentcreatewithurl-fails-toll-free-bridging-of-nsurl-to-cfurlref

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!