将下载的 PDF 存储到文档目录不起作用

Storing Downloaded PDF To Documents Directory Not Working

我有以下代码,我不想解释为什么要这样做,但由于某种原因,它不起作用。 stringURL 工作正常,它取回数据,但无法写入文档目录。这是我第一次使用文件,并且一直在竭尽全力试图让它发挥作用。请问有人能给我指出正确的方向吗?

+ (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];
      });
   });
}

您正在尝试将文件写入 Documents 文件夹的子文件夹。这是失败的,因为子文件夹不存在。您需要先创建文件夹,然后才能写入。

您还应该稍微清理一下代码。并使用更好的NSData方法写入文件。

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);
}