在不加载资源的情况下获取PHAsset的文件大小?

问题描述 投票:0回答:4

有没有办法在不执行

PHAsset
或将其转换为
requestImageDataForAsset
的情况下获取
ALAsset
磁盘上的文件大小?我正在加载用户照片库的预览(可能有数千个),对于我的应用程序来说,他们必须在导入之前知道尺寸。

swift image phasset photolibrary
4个回答
31
投票

您可以获取 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))
 }

4
投票

环球银行金融电信协会5.0 轻松简单:

private static let bcf = ByteCountFormatter()

func getSize(asset: PHAsset) -> String {
    let resources = PHAssetResource.assetResources(for: asset)

    guard let resource = resources.first,
          let unsignedInt64 = resource.value(forKey: "fileSize") as? CLong else {
              return "Unknown"
          }

    let sizeOnDisk = Int64(bitPattern: UInt64(unsignedInt64))
    Self.bcf.allowedUnits = [.useMB]
    Self.bcf.countStyle = .file
    return Self.bcf.string(fromByteCount: sizeOnDisk)
}

2
投票

更安全的解决方案:

[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)")
    }
}

受到如何从 PHAsset 获取 ALAsset URL?

的启发

2
投票

请尝试这个。

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"
}
© www.soinside.com 2019 - 2024. All rights reserved.