How to get the size (KB) of a Video AVAsset

avasset, ios

Solution

Here is a simple Swift 4.x / 3.x extension to get you the size of any `AVURLAsset`:

import AVFoundation

extension AVURLAsset {
    var fileSize: Int? {
        let keys: Set<URLResourceKey> = [.totalFileSizeKey, .fileSizeKey]
        let resourceValues = try? url.resourceValues(forKeys: keys)

        return resourceValues?.fileSize ?? resourceValues?.totalFileSize
    }
}

This returns an optional `Int`, since both `resourceValues.fileSize` and `resouceValues.totalFileSize` return optional Ints.

While it is certainly possible to modify it to return a 0 instead of nil, I choose not to since that would not be accurate. You do not know for sure that it is size 0, you just can't get the value.

To call it:

let asset = AVURLAsset(url: urlToYourAsset)
print(asset.fileSize ?? 0)

If the size returns nil, than it will print 0, or a different value if you so choose.

Problem

I would like to get an `AVAsset` video file size, not the video's resolution, but the file weight in KB. A solution would be to calculate an estimated filesize from the duration and the estimatedDataRate, but this seems to be a lot just to get a filesize. I have checked all data embedded in `AVAssetTrack` it doesn't seems to be in there. Even an estimated filesize would be nice.

Original source