【发布时间】:2016-07-21 19:08:23
【问题描述】:
我正在从 JSON 保存 PDF。当我导航到 App Documents Directory 中的文件路径以验证我是否拥有正确的文件并尝试打开 PDF 时,我无法打开 PDF,并且出现以下错误:
文件路径很好,文档在那里,但它刚刚被损坏或什么的。我假设这与NSData 有关,但我不确定我做错了什么。有什么想法吗?谢谢!
视图控制器:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSLog(@"Downloading PDF Started");
// Get selected PDF
NSString *pdfSelected = self.pdfArray[indexPath.row];
NSLog(@"PDFSl: %@", pdfSelected);
NSData *pdfData = [NSData dataWithContentsOfURL:[NSURL URLWithString:pdfSelected]];
NSLog(@"PDFData: %@", pdfData);
NSString *pdfPath =[documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@%ld.pdf",@"savedPDF", (long)indexPath.row]];
dispatch_async(dispatch_get_main_queue(), ^{
[pdfData writeToFile:pdfPath atomically:YES];
NSLog(@"PDF File Saved!");
NSLog(@"PDF File Path: %@", pdfPath);
// Save PDF path in defaults for evaluation in Details
[defaults setObject:pdfPath forKey:@"cachedPDFPath"];
});
});
JSON sn-p:
{
"fname": "Nadene",
"lname": "Feehan",
"email": "nadene.feehan@gmail.com",
"phone": "(152) 555-5321",
"image": "http://logok.org/wp-content/uploads/2014/04/Apple-logo-grey-880x625.png",
"video": "https://github.com/versluis/Movie-Player/blob/master/Movie%20Player/video.mov?raw=true",
"pdf": "http://adcdownload.apple.com/Developer_Tools/Xcode_8_beta_3/Release_Notes_for_Xcode_8_beta_3.pdf"
},
控制台:
PDFSl:http://adcdownload.apple.com/Developer_Tools/Xcode_8_beta_3/Release_Notes_for_Xcode_8_beta_3.pdf
PDFDataLength: 2070
PDF File Path: /Users/user/Library/Developer/CoreSimulator/Devices/1/data/Containers/Data/Application/A/Documents/savedPDF0.pdf
我也试过了:
NSData *pdfData = [NSData dataWithContentsOfURL:[NSURL URLWithString:pdfSelected] options:NSDataReadingUncached error:&errorPDF]; 但是当我检查控制台看到错误时,没有PDFDataError: (null)
【问题讨论】:
-
您能否显示控制台日志的内容(特别是您显示的日志记录语句的结果)?另外,当你记录
PDFData时,你还能记录数据的长度(即pdfData.length)吗?此外,如果这没有显示出任何有趣的内容,您可以尝试使用dataWithContentsOfURL:options:error:代替更简单的dataWithContentsOfURL:来查看您是否真的并且成功地下载了数据。 -
@fullofsquirrels 没问题,只是添加了控制台日志。有什么让你印象深刻的吗?
-
如果您没有使用开发者帐户登录,该 URL 似乎已被锁定;当我在没有先登录的情况下尝试它时,我被重定向到此页面:developer.apple.com/unauthorized 您可能需要弄清楚如何处理未登录其开发人员帐户的用户(并且,为了让事情更多复杂,我相信 developer.apple.com 会在您闲置 20 分钟或一小时后自动退出),而且它看起来不像简单地检查 HTTP 状态/错误代码那么简单。
-
结束循环,developer.apple.com/unauthorized 的内容只是直接的 HTML,所以 PDF 解析器几乎肯定会崩溃。
-
@fullofsquirrels 这很有意义,我不确定如果没有你的帮助,我需要多长时间才能遇到这个问题。我认为唯一有帮助的事情就是让我神奇地退出开发者帐户,然后也许我就会明白发生了什么。谢谢!如果您作为答案发布,我可以接受!
标签: ios objective-c json pdf