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.