简体   繁体   中英

How to convert NSString path to CFURLRef (for iOS 3.1)?

I display a PDF in a UIScrollView. To do so I use:

myDocumentRef = CGPDFDocumentCreateWithURL((CFURLRef)[[NSBundle mainBundle] URLForResource:@"salonMap" withExtension:@"pdf"]);

Now, I try to make it work on an IOS 3.1 (NSBundle URLForResource:withExtension does not exist for 3.1)

I turned my code into:

NSString *fullPath =  [[NSBundle mainBundle] pathForResource:@"salonMap" ofType:@"pdf"];
NSLog(@"%@", fullPath);
CFStringRef fullPathEscaped = CFURLCreateStringByAddingPercentEscapes(NULL,(CFStringRef)fullPath, NULL, NULL,kCFStringEncodingUTF8);
CFURLRef urlRef = CFURLCreateWithString(NULL, fullPathEscaped, NULL);
myDocumentRef = CGPDFDocumentCreateWithURL(urlRef);

But it leads to a

<Error>: CFURLCreateDataAndPropertiesFromResource: failed with error code -15

I precise that NSLog logs

/var/mobile/Applications/1CF69390-85C7-45DA-8981-A279464E3249/myapp.app/salonMap.pdf"

How do I fix this?

NSURL is interchangeable with CFURLRef thanks to toll-free bridging. Try this:

NSString *pdfPath = [[NSBundle mainBundle] 
                     pathForResource:@"salonMap" ofType:@"pdf"];
NSURL *pdfUrl = [NSURL fileURLWithPath:pdfPath];
CGPDFDocumentRef pdfRef = CGPDFDocumentCreateWithURL((CFURLRef)pdfUrl);

It's important to mention that this will no longer work if you are using ARC. As a result you will need to create a bridged cast. See below:

NSString *pdfPath = [[NSBundle mainBundle] 
                 pathForResource:@"salonMap" ofType:@"pdf"];
NSURL *pdfUrl = [NSURL fileURLWithPath:pdfPath];
CGPDFDocumentRef pdfRef = CGPDFDocumentCreateWithURL((__bridge CFURLRef)pdfUrl);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM