gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 21:35:39 26 4
gpt4 key购买 nike

我有以下代码,我不想弄明白为什么我要这样做,但是由于某种原因,这是行不通的。 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);
}

关于ios - 将下载的PDF存储到文档目录不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34035157/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com