我有以下代码,我不想了解为什么我这样做,但由于某种原因,这是行不通的。 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];
});
});
}
答案 0 :(得分:2)
您正在尝试将文件写入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);
}