Search code examples
pdfios8uiwebviewnsdocumentdirectorywritetofile

Save locally generated PDF to app's documents folder in iOS8


It would seem that my apps no longer are able to save files to their documents folder when doing this:

        NSString *path = [documentsDirectory stringByAppendingPathComponent:fileName];

        NSData *dta = [[NSData alloc] init];
        dta = [NSData dataWithContentsOfFile:path];

        NSLog(@"writing file: %@", path);


        if ([dta writeToFile:path options:NSAtomicWrite error:nil] == NO) {
            NSLog(@"writeToFile error");

        }else {

            NSLog(@"Written: %@", path);
            [self addSkipBackupAttributeToItemAtURL:[NSURL fileURLWithPath:path]];
        }

I do get "Written" in the log with the full path: Written: /var/mobile/Containers/Data/Application/ECBCD65D-A990-4758-A07F-ECE48E269278/Documents/9d440408-4758-4219-9c9c-12fe69cf82f2_pdf.pdf

And as long as I don't quit the app I can load the PDF in a UIWebView like this (pdfPath is a string that I pass to the function that loads the PDF file):

[www loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:pdfPath]]];

Any help at all is as always greatly appreciated.


Solution

  • Okay, after mucking about I found that since the documents directory changes path every time I run the app, I had to:

    1. Write the file to the documents folder with the complete path to the file:

      NSArray *paths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask ,YES ); NSString *documentsDirectory = [paths objectAtIndex:0]; NSString *path = [documentsDirectory stringByAppendingPathComponent: fileName];

      NSData *dta = [[NSData alloc] init];
      dta = [NSData dataWithContentsOfFile:path];
      
      if ([dta writeToFile:path options:NSAtomicWrite error:nil] == NO) {
          NSLog(@"writeToFile error");
      
      }else {
      
          NSLog(@"Written: %@", path);
          [self addSkipBackupAttributeToItemAtURL:[NSURL fileURLWithPath:path]];
      }
      
    2. Save only the file name to my database

    3. Load the file by using the full newly generated Documents directory path and append the file name from my database:

      NSArray *paths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; NSString *path = [documentsDirectory stringByAppendingPathComponent: pdfPath];