Carmen  Grimes

Carmen Grimes

1599176526

Video Download/Disk Cache in iOS : Swift

Video is one of the most vital kind of content now a days. Every application may need to have some kind of video content to tempt their users. But problem comes when app needs to get data for same video number of times, this is not fair for our app user as we are unnecessarily consuming user network data. Specially for short videos, a user can play the same track five times a day and he can fell asleep😴🥱 while looking at loading activity if it appears every time, other case as if you are on Mars 😄 😄 or in a cave and want to enjoy your favourite videos, you may see a message like “No Internet Available” 😔😔. As an application Developer, a first question comes to your mind - Can we cache few most recent videos to improve our user experience? In this article I am going to explore couple of techniques to cache video content on disk using AVFoundation family.


  1. Using AVAssetExportSession

AVAssetExportSession is one of the straight forward way to download video and save it to disk. First we create AVURLAsset and compose audio and video files as shown in below code snippet :

private func exportVideo(forAsset asset: AVURLAsset) {
	        if !asset.isExportable { return }
	        //1
	        let composition = AVMutableComposition()

	        //2
	        if let compositionVideoTrack = composition.addMutableTrack(withMediaType: AVMediaType.video, preferredTrackID: CMPersistentTrackID(kCMPersistentTrackID_Invalid)),
	           let sourceVideoTrack = asset.tracks(withMediaType: .video).first {
	            do {
	                try compositionVideoTrack.insertTimeRange(CMTimeRangeMake(start: CMTime.zero, duration: asset.duration), of: sourceVideoTrack, at: CMTime.zero)
	            } catch {
	                print("Failed to compose video file")
	                return
	            }
	        }
	        //3
	        if let compositionAudioTrack = composition.addMutableTrack(withMediaType: AVMediaType.audio, preferredTrackID: CMPersistentTrackID(kCMPersistentTrackID_Invalid)),
	           let sourceAudioTrack = asset.tracks(withMediaType: .audio).first {
	            do {
	                try compositionAudioTrack.insertTimeRange(CMTimeRangeMake(start: CMTime.zero, duration: asset.duration), of: sourceAudioTrack, at: CMTime.zero)
	            } catch {
	                print("Failed to compose audio file")
	                return
	            }
	        }

	        //4
	        guard let exporter = AVAssetExportSession(asset: composition, presetName: AVAssetExportPresetMediumQuality) else {
	            print("Failed to create export session")
	            return
	        }

	        //5
	        let fileName = asset.url.lastPathComponent
	        let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last!
	        let dirPath = documentsDirectory.appendingPathComponent("Video")
	        let outputURL = dirPath.appendingPathComponent(fileName)
	        print("File path: \(outputURL)")

	        exporter.outputURL = outputURL
	        exporter.outputFileType = AVFileType.mp4

	        //6
	        exporter.exportAsynchronously {
	            if let error = exporter.error {
	                print("Error \(error)")
	            } else {
	                 print("Exporter completed")
	            }
	        }
	    }

#video-downloader #avfoundation #ios #video-cache #swift

What is GEEK

Buddha Community

Video Download/Disk Cache in iOS : Swift
Carmen  Grimes

Carmen Grimes

1599176526

Video Download/Disk Cache in iOS : Swift

Video is one of the most vital kind of content now a days. Every application may need to have some kind of video content to tempt their users. But problem comes when app needs to get data for same video number of times, this is not fair for our app user as we are unnecessarily consuming user network data. Specially for short videos, a user can play the same track five times a day and he can fell asleep😴🥱 while looking at loading activity if it appears every time, other case as if you are on Mars 😄 😄 or in a cave and want to enjoy your favourite videos, you may see a message like “No Internet Available” 😔😔. As an application Developer, a first question comes to your mind - Can we cache few most recent videos to improve our user experience? In this article I am going to explore couple of techniques to cache video content on disk using AVFoundation family.


  1. Using AVAssetExportSession

AVAssetExportSession is one of the straight forward way to download video and save it to disk. First we create AVURLAsset and compose audio and video files as shown in below code snippet :

private func exportVideo(forAsset asset: AVURLAsset) {
	        if !asset.isExportable { return }
	        //1
	        let composition = AVMutableComposition()

	        //2
	        if let compositionVideoTrack = composition.addMutableTrack(withMediaType: AVMediaType.video, preferredTrackID: CMPersistentTrackID(kCMPersistentTrackID_Invalid)),
	           let sourceVideoTrack = asset.tracks(withMediaType: .video).first {
	            do {
	                try compositionVideoTrack.insertTimeRange(CMTimeRangeMake(start: CMTime.zero, duration: asset.duration), of: sourceVideoTrack, at: CMTime.zero)
	            } catch {
	                print("Failed to compose video file")
	                return
	            }
	        }
	        //3
	        if let compositionAudioTrack = composition.addMutableTrack(withMediaType: AVMediaType.audio, preferredTrackID: CMPersistentTrackID(kCMPersistentTrackID_Invalid)),
	           let sourceAudioTrack = asset.tracks(withMediaType: .audio).first {
	            do {
	                try compositionAudioTrack.insertTimeRange(CMTimeRangeMake(start: CMTime.zero, duration: asset.duration), of: sourceAudioTrack, at: CMTime.zero)
	            } catch {
	                print("Failed to compose audio file")
	                return
	            }
	        }

	        //4
	        guard let exporter = AVAssetExportSession(asset: composition, presetName: AVAssetExportPresetMediumQuality) else {
	            print("Failed to create export session")
	            return
	        }

	        //5
	        let fileName = asset.url.lastPathComponent
	        let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last!
	        let dirPath = documentsDirectory.appendingPathComponent("Video")
	        let outputURL = dirPath.appendingPathComponent(fileName)
	        print("File path: \(outputURL)")

	        exporter.outputURL = outputURL
	        exporter.outputFileType = AVFileType.mp4

	        //6
	        exporter.exportAsynchronously {
	            if let error = exporter.error {
	                print("Error \(error)")
	            } else {
	                 print("Exporter completed")
	            }
	        }
	    }

#video-downloader #avfoundation #ios #video-cache #swift

Best Swift iOS App Development Company in USA & India

Are you looking for the best swift iOS App Development Company in USA & India? We at AppClues Infotech is one of the leading Swift iOS App development company that help to build Innovative, Secure & high-performance mobile app with modern features & technology.

For more info:
Website: https://www.appcluesinfotech.com/
Email: info@appcluesinfotech.com
Call: +1-978-309-9910

#swift ios app development company in usa & india #swift ios app development company in usa #hire swift ios app developers in usa #top swift ios app development company #best swift ios app development company in usa #app development company in usa & india

Sapna Chaudhary New Haryanvi Song 2021 | Haryanvi Songs Download

Sapna Dance Video Download 2021https://www.newharyanvivideo.com/sapna-chaudhary-new-haryanvi-song-2021-haryanvi-songs-download/
Sapna New Song Video Download Sapna Dance Video Download
Sapna New Hd Video Download Haryanvi Dance Video Download
Sapna Stage Dance Video Download
Sapna Dance MP4, HD MP4 Video Download,New Song, Sapna Ki New Video Song, Sapna Ki Hot Viideo
Sapna New Mast Video, Sapna New Hd Video Download

#sapna dance #sapna dance video #sapna dance video download 2021, #sapna new song video download 2021 , #sapna dance video download , #sapna new hd video download ,

Top Swift iOS App Development Company in USA

Are you looking for a Top Swift iOS App Development Company in USA? AppClues Infotech is a top Swift iOS App Development Company in USA that offers cutting-edge services to businesses for their custom requirements. Hire Dedicated Swift iOS Mobile Apps Developer & Programmers from AppClues Infotech at an affordable cost.

For more info:
Website: https://www.appcluesinfotech.com/
Email: info@appcluesinfotech.com
Call: +1-978-309-9910

#top swift app development company usa #best swift app development company #swift app development #swift ios app development #swift app development company #best swift ios app development company in usa

Hire Expert Swift iOS App Developers in USA

Are you looking to hire the best swift iOS developers for your iPhone or iPad App project? AppClues Infotech is a top-rated iOS app development company in the USA. Hire our dedicated swift iOS app developers to build feature-rich and robust iOS app.

For more info:
Website: https://www.appcluesinfotech.com/
Email: info@appcluesinfotech.com
Call: +1-978-309-9910

#top swift app development company usa #best swift app development company #swift app development #swift ios app development #swift app development company #hire expert swift ios app developers in usa