Jude Michael Murphy
Jude Michael Murphy

Reputation: 1198

Storing Downloaded PDF To Documents Directory Not Working

I have the following code, I don't want to get into why I am doing it this way, but for some reason this is not working. The stringURL is working fine, it gets data back, but fails to write to the document directory. This is the first time I'm working with files, and have been pulling my hair out trying to get this to work. Please could someone point me in the right direction?

+ (void) downloadAndStorePDFFromURLWithString: (NSString *) stringURL andFileID: (NSString *) fileID andTitle: (NSString *) title;
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
       NSData *pdfData = [[NSData alloc] initWithContentsOfURL: [NSURL URLWithString: stringURL]];

       dispatch_async(dispatch_get_main_queue(), ^(void) {
          //STORE THE DATA LOCALLY AS A PDF FILE
          NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
          NSString *documentsDirectory = [paths objectAtIndex:0];
          documentsDirectory = [[paths objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat: @"%@/%@", fileID, title]];

          //GET LOCAL FILE PATH OF DOWNLOADED PDF
          //NSLog(@"SUCCESSFULLY DOWNLOADED DOCUMENT FOR FILE: %@ WILL BE STORED AT %@", fileID, documentsDirectory);
          BOOL success = [pdfData writeToFile: documentsDirectory atomically: YES];
          NSLog(success ? @"Yes" : @"No");

          //TELL TABLEVIEW TO RELOAD
          //[[NSNotificationCenter defaultCenter] postNotificationName: @"DocumentDownloaded" object: nil];

          //SAVE FILEPATH URL IN NSUSERDEFAULTS
          //[PDFDownloadManager addURLToListOfSavedPDFs: [PDFDownloadManager filePath: fileID andTitle: title] andFileID: fileID];
      });
   });
}

Upvotes: 0

Views: 552

Answers (1)

rmaddy
rmaddy

Reputation: 318774

You are attempting to write the file to a subfolder of the Documents folder. This is failing because the subfolder doesn't exist. You need to create the folder before you can write to it.

You should also clean up the code a bit. And use the better NSData method to write the file.

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *folder = [documentsDirectory stringByAppendingPathComponent:fileID];
[[NSFileManager defaultManager] createDirectoryAtPath:folder withIntermediateDirectories:YES attributes:nil error:nil];
NSString *filePath = [folder stringByAppendingPathComponent:title];

NSError *error = nil;
BOOL success = [pdfData writeToFile:filePath options: NSDataWritingAtomic error:&error];
if (!success) {
    NSLog(@"Error writing file to %@: %@", filePath, error);
}

Upvotes: 2

Related Questions