Search code examples
iospdfuiwebviewnsdictionarynsurl

Save NSURL's PDF Locally - Retrieve


Hello,

How would I retrieve an NSUrl's PDF locally from a NSDictionary. I save it like so:

NSData *pdfData = [[NSData alloc] initWithContentsOfURL:[
    NSURL URLWithString:@"http://www.example.com/info.pdf"]];

// Store the Data locally as PDF File
NSString *resourceDocPath = [[NSString alloc] initWithString:[
    [[[NSBundle mainBundle] resourcePath] stringByDeletingLastPathComponent]
        stringByAppendingPathComponent:@"Documents"
]];

NSString *filePath = [resourceDocPath 
    stringByAppendingPathComponent:@"myPDF.pdf"];
[pdfData writeToFile:filePath atomically:YES];


// Now create Request for the file that was saved in your documents folder
NSURL *url = [NSURL fileURLWithPath:filePath];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];

[webView setDelegate:self];
[webView loadRequest:requestObj];

But how would I retrieve the file and display it in a UIWebView??

Cheers, SebOH


Solution

  • You are doing the exact thing, "retrieve the file and display it in a UIWebView??" using the below code

    // Now create Request for the file that was saved in your documents folder
    NSURL *url = [NSURL fileURLWithPath:filePath];
    NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
    
    [webView setDelegate:self];
    [webView loadRequest:requestObj];
    

    Is there some problem you are facing with the above lines of code, is the PDF loading in the webview?

    So if you don't want to download the file every time do this check,

    if (![[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
    //download the file
    }
    

    So the whole solution would be

    // Store the Data locally as PDF File
    NSString *resourceDocPath = [[NSString alloc] initWithString:[
        [[[NSBundle mainBundle] resourcePath] stringByDeletingLastPathComponent]
            stringByAppendingPathComponent:@"Documents"
    ]];
    
    NSString *filePath = [resourceDocPath 
        stringByAppendingPathComponent:@"myPDF.pdf"];
    
    if (![[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
            //download the file
            NSData *pdfData = [[NSData alloc] initWithContentsOfURL:[
            NSURL URLWithString:@"http://www.example.com/info.pdf"]];
            [pdfData writeToFile:filePath atomically:YES];
        }
    
    // Now create Request for the file that was saved in your documents folder
    NSURL *url = [NSURL fileURLWithPath:filePath];
    NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
    
    [webView setDelegate:self];
    [webView loadRequest:requestObj];