This is pretty frustrating. I'm trying to get the size of an AVURLasset, but try to avoid naturalSize
since Xcode tells me, this is deprecated in iOS5.
But: What's the replacement?
I can't find any clue on how to get the video-dimensions without using «naturalsize»...
The deprecation warning on the official documentation suggests, "Use the
naturalSize
andpreferredTransform
, as appropriate, of the asset’s video tracks instead (see alsotracksWithMediaType:
)."I changed my code from:
to
It's less pretty and less safe now but won't break when they drop that method.
This is a fairly simple extension for
AVAsset
in Swift 4 to get the size of the video, if available:The deprecation warning says:
So we need an AVAssetTrack, and we want its naturalSize and preferredTransform. This can be accessed with the following:
asset is obviously your AVAsset.
I just checked the documentation online, and the
naturalSize
method is deprecated for the AVAsset object. However, there should always be an AVAssetTrack which refers to the AVAsset, and the AVAssetTrack has anaturalSize
method that you can call.Via: AVAssetTrack Reference for iOS
To derive the dimension of an
AVAsset
, you should calculate the union of all the visual track rects (after applying their corresponding preferred transformation):Methods that rely on
CGSizeApplyAffineTransform
fail when your asset contains tracks with non-trivial affine transformation (e.g., 45 degree rotations) or if your asset contains tracks with different origins (e.g., two tracks playing side-by-side with the second track's origin augmented by the width of the first track).See:
MediaPlayerPrivateAVFoundationCF::sizeChanged()
at https://opensource.apple.com/source/WebCore/WebCore-7536.30.2/platform/graphics/avfoundation/cf/MediaPlayerPrivateAVFoundationCF.cppResolution in Swift 3:
For Swift 4:
Solutions without
preferredTransform
do not return correct values for some videos on the latest devices!