【问题标题】:PDF file size from document directory showing zero in iOS文档目录中的 PDF 文件大小在 iOS 中显示为零
【发布时间】:2014-07-20 08:54:09
【问题描述】:

我正在使用以下代码检索位于文档目录中的 PDF 文件的文件大小。

- (NSString *)sizeOfFile:(NSString *)filePath {
    NSDictionary *fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:filePath error:nil];
    NSInteger fileSize = [[fileAttributes objectForKey:NSFileSize] integerValue];
    NSString *fileSizeString = [NSByteCountFormatter stringFromByteCount:fileSize countStyle:NSByteCountFormatterCountStyleFile];
    return fileSizeString;
}



NSURL *url = [self.arrayOfBooks objectAtIndex:indexPath.row];
NSLog(@"%@",[self sizeOfFile:url.absoluteString]); // Showing zero KB.

我确定arrayBooks 中有文件,因为它可以显示在cellForRowAtIndexPath 中。

但我不知道为什么文件大小显示为零。

请帮帮我。

【问题讨论】:

  • 您是否验证过filePath 确实存在?您是否确认fileAttributes 不是nil?使用error 参数到attributesOfItemAtPath:error:
  • fileAttributes 显示为零。但是filePath是正确的。
  • 再次,使用error 参数查看为什么fileAttributesnil
  • 错误信息是 .错误域=NSCocoaErrorDomain 代码=260“操作无法完成。(Cocoa 错误 260。)”UserInfo=0x10934b640 {NSFilePath=file:///Users/user/Library/Application%20Support/iPhone%20Simulator/7.1- 64/Applications/08BE9071-6251-44ED-A8E0-55CD478380FC/Documents/myPDFFile.pdf, NSUnderlyingError=0x10934b170 "操作无法完成。没有这样的文件或目录"}

标签: ios nsurl nsfilemanager


【解决方案1】:

问题的最可能原因是发送到 sizeOfFile: 的路径无效。

您的代码:

NSURL *url = [self.arrayOfBooks objectAtIndex:indexPath.row];
NSLog(@"%@",[self sizeOfFile:url.absoluteString]); // Showing zero KB.

应该是:

NSURL *url = [self.arrayOfBooks objectAtIndex:indexPath.row];
NSLog(@"%@",[self sizeOfFile:[url path]]);

您想调用path 方法来获取文件路径。 absoluteString 返回文件 URL,而不是路径。

另外,不要使用属性语法来调用方法。

【讨论】:

  • 谢谢。现在我得到了。我不明白不要使用属性语法来调用方法。为什么我不应该使用它。请你解释一下吗?
猜你喜欢
  • 2021-03-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-06
  • 1970-01-01
  • 1970-01-01
  • 2019-08-22
相关资源
最近更新 更多