为什么在 iOS 应用程序中将 PDF 文件写入和保存到 Documents 目录只会间歇性地成功?在我的应用程序中,我从 UIViews 数组创建了一个 PDF,访问 Documents 文件夹并将文件存储在其中。
我估计这在 80% 的时间里都有效。其他 20% 的时间 PDF 被创建(我也通过电子邮件将它发送给自己),但它从未真正写入 Documents 文件夹。
在失败的情况下,我可以通过电子邮件将 PDF 发送给自己,以便我知道它已创建。当我在文件资源管理器中检查 Documents 文件夹时,它是空的。当我注销它的内容时,它也是空的。我正在使用以下代码创建 PDF 并导出到 Documents。
- (NSURL *)applicationDocumentsDirectory
{
return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}
-(void)createPDFfromUIViews:(NSArray *)views saveToDocumentsWithFileName:(NSString*)aFilename andTag:(NSInteger)tag
{
// Creates a mutable data object for updating with binary data, like a byte array
NSMutableData *pdfData = [NSMutableData data];
// Points the pdf converter to the mutable data object and to the UIView to be converted
UIView *view1 = [views objectAtIndex:0];
UIGraphicsBeginPDFContextToData(pdfData, view1.bounds, nil);
CGContextRef pdfContext = UIGraphicsGetCurrentContext();
// draws rect to the view and thus this is captured by UIGraphicsBeginPDFContextToData
for (UIView *view in views)
{
UIGraphicsBeginPDFPage();
[view.layer renderInContext:pdfContext];
}
// remove PDF rendering context
UIGraphicsEndPDFContext();
// Get the path to the documents directory and append the filename of the PDF
NSString *path = [[self applicationDocumentsDirectory].path stringByAppendingPathComponent:aFilename];
NSLog (@"DOCUMENTS DIRECTORY : %@", [self applicationDocumentsDirectory].path);
NSLog (@"DOCUMENTS DIRECTORY WITH FILE PATH : %@", path);
NSError *error = nil;
BOOL success = [pdfData writeToFile:path options:NSDataWritingWithoutOverwriting error:&error];
if (!success)
{
NSLog(@"Error writing PDF: %@", [error localizedDescription]);
}
else
{
if (tag == 1)
{
NSLog(@"PDF Saved With Name %@", aFilename);
[self.navigationController popViewControllerAnimated:YES];
}
else if (tag == 2)
{
[self checkAccountAndComposeEmailWithAttachmentData:pdfData andSubject:aFilename];
}
}
}
更新:修改代码以包含 NSError。给出的错误是“无法完成操作。(Cocoa 错误 4。)
更新 2:修改了代码以包含 Apple 推荐的获取 Documents 目录的方法。还添加了许多日志以显示我得到了正确的目录/文件路径 - 两者都按预期显示了 Documents 文件夹或 Documents/File Name。NSFileNoSuchFileError
每次仍然作为错误返回。