iOS中系统的PHAsset图片、视频计算存储大小

//相簿列表项
struct HGImageAlbumItem {
    //相簿名称
    var title:String?
    //相簿内的资源
    var fetchResult:NSMutableArray?
}

 

第一种: 1. 计算系统的图片大小

// MARK: 统计系统图片的总大小
    func statisticPictureAssetsAllSize(items: inout [HGImageAlbumItem]) -> Int64 {
        var fileAllSizeB: Int64 = 0
        let requestOptions = PHImageRequestOptions.init()
        requestOptions.isSynchronous = true
        for result in items {
            result.fetchResult?.enumerateObjects({ (object, index, isStop) in
                let imageManager = PHImageManager.default()
                imageManager.requestImageData(for: object as! PHAsset, options: requestOptions, resultHandler: { (imageData, dataUTI, orientation, info) in
                    if imageData != nil {
                        fileAllSizeB += Int64(imageData!.count);   // 图片大小,单位B
                    }
                })
            })
        }
        
        return fileAllSizeB
    }

2. 计算系统的视频大小

// MARK: 统计系统视频的总大小
    func statisticVideoAssetsAllSize(items: inout [HGImageAlbumItem]) -> Int64 {
        var fileAllSizeB: Int64 = 0
        let requestOptions = PHVideoRequestOptions.init()
        requestOptions.version = .original
        for result in items {
            result.fetchResult?.enumerateObjects({ (object, index, isStop) in
                let imageManager = PHImageManager.default()
                imageManager.requestAVAsset(forVideo: object as! PHAsset, options: requestOptions, resultHandler: { (asset, audioMix, info) in
                    if asset is AVURLAsset {
                        let urlAsset = asset as! AVURLAsset
                        fileAllSizeB += urlAsset.value(forKey: URLResourceKey.fileSizeKey.rawValue) as! Int64
                    }
                })
            })
        }
        
        return fileAllSizeB
    }

第二种:(一个方法,按照图片和视频都是文件的理论查找计算)

// MARK: 统计系统文件的总大小
    func statisticFileAssetsAllSize(items: inout [HGImageAlbumItem]) -> Int64 {
        var fileAllSizeB: Int64 = 0
        for result in items {
            result.fetchResult?.enumerateObjects({ (object, index, isStop) in
                let resource = PHAssetResource.assetResources(for: object as! PHAsset).first
                fileAllSizeB += (resource?.value(forKey: "fileSize"))! as! Int64
            })
        }
        
        return fileAllSizeB
    }

个人建议用第二种方法去统计,相对精简(也应对了一切皆是文件的思想)

你可能感兴趣的:(swift语言开发,iOS软件开发,image,video,swift,PHAsset,statistic)