获取PHAsset的文件大小而不加载资源?

时间:2017-07-14 19:58:06

标签: swift image phasset photolibrary

有没有办法在PHAsset的磁盘上获取文件大小而不执行requestImageDataForAsset或将其转换为ALAsset?我正在加载用户照片库的预览 - 可能有成千上万的照片库 - 我的应用程序必须知道他们在导入之前知道大小。

3 个答案:

答案 0 :(得分:13)

您可以抓取PHAsset的fileSize并将其转换为人类可读的形式,如下所示:

      let resources = PHAssetResource.assetResources(for: yourAsset) // your PHAsset

      var sizeOnDisk: Int64? = 0

      if let resource = resources.first {
        let unsignedInt64 = resource.value(forKey: "fileSize") as? CLong
        sizeOnDisk = Int64(bitPattern: UInt64(unsignedInt64!))
      }

然后使用您的sizeOnDisk变量并将其传递给这样的方法......

func converByteToHumanReadable(_ bytes:Int64) -> String {
     let formatter:ByteCountFormatter = ByteCountFormatter()
     formatter.countStyle = .binary

     return formatter.string(fromByteCount: Int64(bytes))
 }

答案 1 :(得分:1)

请尝试这个。

let resources = PHAssetResource.assetResources(for: YourAsset)
var sizeOnDisk: Int64 = 0

if let resource = resources.first {
   let unsignedInt64 = resource.value(forKey: "fileSize") as? CLong
   sizeOnDisk = Int64(bitPattern: UInt64(unsignedInt64!))

   totalSize.text = String(format: "%.2f", Double(sizeOnDisk) / (1024.0*1024.0))+" MB"
}

答案 2 :(得分:0)

更安全的解决方案:

[asset requestContentEditingInputWithOptions:nil completionHandler:^(PHContentEditingInput * _Nullable contentEditingInput, NSDictionary * _Nonnull info) {
    NSNumber *fileSize = nil;
    NSError *error = nil;
    [contentEditingInput.fullSizeImageURL getResourceValue:&fileSize forKey:NSURLFileSizeKey error:&error];
    NSLog(@"file size: %@\nerror: %@", fileSize, error);
}];

快速版本:

asset.requestContentEditingInput(with: nil) { (contentEditingInput, _) in
    do {
        let fileSize = try contentEditingInput?.fullSizeImageURL?.resourceValues(forKeys: [URLResourceKey.fileSizeKey]).fileSize
        print("file size: \(String(describing: fileSize))")
    } catch let error {
        fatalError("error: \(error)")
    }
}

受到How to get an ALAsset URL from a PHAsset?

的启发