Search code examples
swiftphassetavasset

Read Gallery Video in Custom Size


How could I get a video from Gallery(Photos) in custom format and size.

for example I want to read a video in 360p.

I used below code to get video data but apple said it doesn't guarantee to read it in lowest quality.

It's a PHAsset extension, so self refering to a PHAsset object.

var fileData: Data? = nil
let manager = PHImageManager.default()
let options = PHVideoRequestOptions()
options.isNetworkAccessAllowed = true
options.deliveryMode = .fastFormat

manager.requestAVAsset(forVideo: self, options: options) {
    (asset: AVAsset?, audioMix: AVAudioMix?, _) in
    if let avassetURL = asset as? AVURLAsset {
        guard let video = try? Data(contentsOf: avassetURL.url) else {
            print("reading video failed")
            return
        }
        fileData = video
    }
}

Solution

  • There is a simple reason it can't be guaranteed: The file in 360p might not be on the device or in the cloud. So the Photos framework will deliver a format nearest to what you request. If you want exactly 360p, I would recommend you reencode the video you get from the photos framework yourself.