问题
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