Bacancy Bacancy
      • About Company
      • Resources

      About Company

      About Us Leadership Team Customer Reviews Awards & Recognition
      Infrastructure Our Locations Partnership

      Resources

      Press Room Blog Insights
      We are great place to work certified™

      Building and Sustaining High-Trust, High-Performance Culture

      Get Quote
    • Engagement Models

      Hiring Software Developers becomes easier with just a few clicks.

      Software Development Outsourcing

      End-to-end delivery of custom solutions aligned to your roadmap.

      Staff Augmentation

      Scale your in-house team with pre-vetted specialists on demand.

      Dedicated Teams

      Get dedicated engineers who work exclusively on your project.

      • Enterprise Services
      • IT Services
      • Data Analytics
      • Cloud Services
      • AI & ML
      • Platforms

      Enterprise Services

      Digital Transformation Business Process Automation Digital Product Engineering Enterprise App Development Custom Software Development

      IT Services

      Legacy App Modernization DevOps & SRE Full Stack Development AI Testing & QA Automation

      Data Analytics

      Data Visualization & Reporting Data Engineering & Pipelines Data Science & Predictive Analytics Business Intelligence

      Cloud Services

      Cloud Strategy & Consulting Cloud Migration & Modernization Multi Cloud Management

      AI & ML

      AI Development Agentic AI Generative AI Computer Vision Machine Learning & MLOps

      Platforms

      Salesforce SAP ServiceNow Microsoft Dynamics Snowflake
      High-quality, Cost-effective IT Outsourcing

      Schedule a free discovery session to explore your needs and find tailored solutions with no obligation.

      explore all services
    • Industries
      Healthcare Fintech Real Estate
      Logistics Education Retail & Ecommerce
      Let's Grow Together! Get Quote
      • Front End
      • Backend
      • Mobile
      • Databases
      • DevOps & Infra
      • AI & Data Stack
      • Vibe Coding

      Front End

      React.js Next.js Angular Vue.js TypeScript
      Your Very Own UI/UX Architects

      Experience smooth navigation and user-friendly designs with our front-end expertise.

      Hire Frontend Developer

      Backend

      Node.js Python Java Spring Boot Laravel .NET C# Golang FastAPI
      Server Solutions To Change Power Dynamics

      Transform your data into digital experiences with optimized coding standards.

      Hire Backend Developer

      Mobile

      iOS Android Flutter React Native
      Innovating Mobile-Friendly App Solutions

      Create dynamic mobile apps that make your brand stand out from the crowd.

      Hire Mobile App Developer

      Databases

      PostgreSQL MongoDB MySQL Redis Supabase
      Dedicated Talent With Skilled Approach

      Bring your digital visions to life with a hired resource at your convenience.

      Hire Dedicated Developer

      DevOps & Infra

      AWS Azure Google Cloud Docker Kubernetes Terraform
      Redefining Scalable Digital Infrastructures

      Make your data accessible worldwide at will, and leave the stress behind.

      Get Quote

      AI & Data Stack

      OpenAI LangChain LlamaIndex Apache Spark Airflow Tableau PowerBI Databricks
      Guiding Decisions With Data-Driven Insights

      Transition from your gut calls to actionable insights with our rich Data Science expertise.

      Get Quote

      Vibe Coding

      Base44 Claude Code Cursor Lovable Github Copilot
      Your AI-Native Development Team

      Skip the boilerplate. Our vibe coding experts use AI-first tools to go from prompt to product, fast.

      Hire Vibe Coding Developer
  • Case Studies
  • Contact Us
Find a Developer book a 30 min call
      • About Us
      • Leadership Team
      • Customer Reviews
      • Awards & Recognition
      • Infrastructure
      • Our Locations
      • Partnership
      • Press Room
      • Blog
      • Insights
      • Digital Transformation
      • Business Process Automation
      • Digital Product Engineering
      • Enterprise App Development
      • Custom Software Development
      • Legacy App Modernization
      • DevOps & SRE
      • Full Stack Development
      • AI Testing & QA Automation
      • Data Visualization & Reporting
      • Data Engineering & Pipelines
      • Data Science & Predictive Analytics
      • Business Intelligence
      • Cloud Strategy & Consulting
      • Cloud Migration & Modernization
      • Multi Cloud Management
      • AI Development
      • Agentic AI
      • Generative AI
      • Computer Vision
      • Machine Learning & MLOps
      • Salesforce
      • SAP
      • ServiceNow
      • Microsoft Dynamics
      • Snowflake
    • Healthcare
    • Fintech
    • Real Estate
    • Logistics
    • Education
    • Retail & Ecommerce
      • React.js
      • Next.js
      • Angular
      • Vue.js
      • TypeScript
      • Hire Frontend Developer
      • Node.js
      • Python
      • Java
      • Spring Boot
      • Laravel
      • .NET
      • C#
      • Golang
      • FastAPI
      • Hire Backend Developer
      • iOS
      • Android
      • Flutter
      • React Native
      • Hire Mobile App Developer
      • PostgreSQL
      • MongoDB
      • MySQL
      • Redis
      • Supabase
      • Hire Dedicated Developer
      • AWS
      • Azure
      • Google Cloud
      • Docker
      • Kubernetes
      • Terraform
      • Get Quote
      • OpenAI
      • LangChain
      • LlamaIndex
      • Apache Spark
      • Airflow
      • Tableau
      • PowerBI
      • Databricks
      • Get Quote
      • Base44
      • Claude Code
      • Cursor
      • Lovable
      • Github Copilot
      • Hire Vibe Coding Developer
  • Case Studies
  • Contact Us
  • Find a Developer
  • book a 30 min call
AVFoundation Framework

AVFoundation Framework: A Hands-on Guideline to Trim the Video

Chirag Patel
Chirag Patel Lead Software Engineer
Last Updated on March 4, 2024 | Written By: Chirag Patel

So, when I started understanding about the AVFoundation Framework, initially, it was a bit difficult to understand, but when I started to apply various methods in real-time, it was so easy to understand.

Let’s have a look at the AVFoundation framework in-detail.

What is AVFoundation?

AVFoundation is a time-based full-featured framework widely used with Swift and Objective-C interfaces that are offering a high level of services to work with time-based audiovisual media on iOS, macOS, watchOS and tvOS. AVFoundtation, let’s you create, play and edit QuickTime movies, HLS streams, and MPEG-4 files incorporating powerful media functionality.

AVfoundation framework is used for detailed level time-based audiovisual data, where you can capture, process, edit, and apply a filter on videos or Audio files.

I am using this functionality in one of my projects, where the users can Merge video over the video, Video over the image, Audio over the image.

Trim Video with AVFoundation and Swift

Getting Started with Code

Nowadays, video trimming is essential functionality, and one of the libraries called UIImagePikerController is already providing this functionality. In this blog, we will be going to have a look at how video files will trim and how we can set the quality of the video.

Objective C
#import < AVFoundation/AVFoundation.h >
Swift
@import AVfundation

Import AVFoundation framework in your usable class

Objective C
 AVURLAsset *asset = [AVURLAsset URLAssetWithURL:URLVideo options:nil];

Swift 
var asset: AVURLAsset = AVURLAsset(URL: self.url)

AVURLAsset Object is used to get metadata of the Video file like Tracks name, Composer info, Video length, and Video Duration.

Objective C
 AVAssetExportSession *exportSession = [[AVAssetExportSession alloc] initWithAsset:asset presetName:AVAssetExportPresetHighestQuality];

Swift
var exporter = AVAssetExportSession(asset: asset, presetName: AVAssetExportPresetHighestQuality)

AVAssetExportSession object fetches the content from the asset object and provides the output of the form described by a specified export preset.

Here we will be required to provide inputs like:

Output URL: Where edited video file will be stored

File Type: Final video type (.mov, .Mp4)

Time Range: Start time and End time for where to trim the video

Objective C

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *outputURL = paths[0];
    NSFileManager *manager = [NSFileManager defaultManager];
    [manager createDirectoryAtPath:outputURL withIntermediateDirectories:YES attributes:nil error:nil];
    outputURL = [outputURL stringByAppendingPathComponent:@"output.mp4"];
    // Remove Existing File
    [manager removeItemAtPath:outputURL error:nil];

Swift
         
        outputURL = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
       let fileManager =  NSFileManager.defaultManager()
fileManager.createDirectoryAtPath(outputURL, withIntermediateDirectories: false, attributes: nil, error: nil)
 outputURL = outputURL.appendingPathComponent(“output.mp4”)

Get the destination path using NSFileManager

 exportSession.outputURL = [NSURL fileURLWithPath:outputURL];

And give that path to exportSession Output URL

exportSession.shouldOptimizeForNetworkUse = YES;
exportSession.outputFileType = AVFileTypeQuickTimeMovie;

Set the OptimizeForNetworkUse to Yes and File type as per your specific requirements.

CMTime startTime = CMTimeMake((int)(floor(0 * 100)), 100);
 CMTime stopTime = CMTimeMake((int)(ceil(CMTimeGetSeconds(videoToTrimSecond) * 100)), 100);
  CMTimeRange range = CMTimeRangeFromTimeToTime(startTime, stopTime);
   
  exportSession.timeRange = range;

Get the Start time and End time in the form of CMTime and Create CMTimeRange set range input to exportSession

Objective C
 [exportSession exportAsynchronouslyWithCompletionHandler:^(void)
     {
             NSLog(@"export did finish...");
            
              [MBProgressHUD hideHUDForView:self.view animated:true];
             if (compressionEncoder.status == AVAssetExportSessionStatusCompleted) {
                 NSURL *outputURL = exportSession.outputURL;
              
                 
             } else {
                 NSLog(@"%li", (long)compressionEncoder.status);
                  NSLog(@"%@", compressionEncoder.error);
             }

    }];

Swift
exportSession.exportAsynchronouslyWithCompletionHandler({
     switch exportSession.status {
        case .failed:
            print("Export failed: \(exportSession.error != nil ? exportSession.error!.localizedDescription : "No Error Info")")
        case .cancelled:
            print("Export canceled")
        case .completed:
            resultClosure(finalOutputUrl!)
        default:
            break
        }

 })

Once you have initialized an export session with the asset that contains the source media, the export preset name and the output file type, you can start the export running by invoking exportAsynchronouslyWithCompletionHandler:

Once the exporting process will finish, it will return the output with completed or failed Status.

You can get the output URL path from the exportSession.outputURL

Sometimes exporting process will take lots of time to give the output, so we need to show some progress of exporting video to the user so the user can wait until the process gets complete

Let’s add a progress bar to the process. We will show progress using the MBProgresHUD

Objective C       

NSTimer   exportProgressBarTimer = [NSTimer scheduledTimerWithTimeInterval:.1 target:self selector:@selector(updateExportDisplay:) userInfo:nil repeats:YES];

MBProgressHUD    *Progresshud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
 Progresshud.mode = MBProgressHUDModeAnnularDeterminate;

Swift

let exportProgressBarTimer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(updateExportDisplay(_:)), userInfo: nil, repeats: true)

let Progresshud = MBProgressHUD.showAdded(to: view, animated: true)
Progresshud?.mode = MBProgressHUDModeAnnularDeterminate

  • First, initialize NStimer Object to call updateExportDisplay with 1 second time interval
  • Second, Initialize the MBProgressHUD object to show a progress bar
Objective c
-(void)updateExportDisplay:(NSTimer *)timer {
    
    Progresshud.progress = exportSession.progress;
    Progresshud.label.text = [NSString stringWithFormat:@"%.0f%%",exporter.progress*100];
    
    
} 

Swift
func updateExportDisplay(_ timer: Timer?) {

    Progresshud.progress = exportSession.progress
    Progresshud.label.text = String(format: "%.0f%%", exporter.progress * 100)


}


Here updateExportDisplay Method will call every 1second, and the method will get Progress from the exportSession.

I hope your purpose of landing on this page is served. We’ve seen in detail how to Trim Video as per your UI requirements using the Advance AVfoundation Framework APIs.

Now all you are required to do is apply the Client’s fancy design and as your main Logic is already ready.

Happy Coding!


Expand Your Digital Horizons With Us.

Start a new project or take an existing one to the next level. Get in touch to start small, scale-up, and go Agile.


Or
E-mail us : solutions@bacancy.com

Your Success Is Guaranteed !

Related Articles

Dipal Bhavsar

July 17, 2025

Application Development

Application Modernization Strategy: A Complete Roadmap for Legacy Transformation

By : Dipal Bhavsar

Application modernization strategies help businesses update legacy systems to meet demanding performance, scalability, and integration needs. They include approaches such...

Read More
Dipal Bhavsar

April 10, 2025

Application Development

AI in Mobile App Development: How It Works, Benefits & What’s Next

By : Dipal Bhavsar

This comprehensive guide explores the ins and outs of AI in mobile app development. From chatbots and automation to smart...

Read More
Hardik Patel

December 19, 2024

Application Development

Web App Development Cost: Detailed Factors & Estimates by Bacancy Expert

By : Hardik N Patel

Web app development cost vary for each project due to features, complexity, functionalities, and scope changes. In this blog, we...

Read More

Offices and Development Centers

Bacancy Ahmedabad Ahmedabad

15-16, Times Corporate Park, Thaltej, Ahmedabad, 380059

Bacancy Gandhinagar Gandhinagar

422-A, 4th Floor, Pragya Tower Road 11, Block 15, Zone 1, SEZ-PA Gandhinagar, 382355

Bacancy Hyderabad Hyderabad

Awfis, Level 1, N Heights, Plot No 38, Phase 2, Hitech City Hyderabad, 500081

Bacancy Mumbai Mumbai

18th Floor, Cyberone, opp. CIDCO Exhibition Centre, Sector 30, Vashi, Navi Mumbai, 400703

Bacancy Pune Pune

2nd FloorMarisoft-1, Marigold IT Park, Pune - 411014

Bacancy Bengaluru Bengaluru

Raheja Towers, 26/27, Mahatma Gandhi Rd, East Wing, Craig Park Layout, Ashok Nagar, Bengaluru, 560001

Global Presence

Bacancy New Jersey New Jersey

33 South Wood Ave, Suite 600, Iselin NJ 08830

Bacancy California California

535 Mission St 14th floor, San Francisco, CA 94105

Bacancy Massachusetts Massachusetts

501 Boylston St, Boston, MA 02116

Bacancy Florida Florida

4995 NW, 72nd Avenue, Suite 307, Miami, FL, 33166

Bacancy London London

90 York Wy, London N1 9AG, United Kingdom

Bacancy Ontario Ontario

71 Dawes Road, Brampton, On L6X 5N9, Toronto

Bacancy Australia Australia

351A Hampstead Rd, Northfield SA 5085

Bacancy UAE UAE

One Central 8th and 9th Floor - Trade Centre - Trade Centre 2 - Dubai - United Arab Emirates

Bacancy Sweden Sweden

Junkergatan 4, 126 53 Hagersten

Get in Touch

Great Place to Work

Get in Touch

cal-icon

Looking for expert advice?

Schedule a Expert Call


  • Brochure
  • Quality Assurance
  • Resources
  • Tutorials
  • Customer Reviews
  • Privacy Policy
  • FAQs
  • Press Room
  • Contact Us
  • Sitemap
  • Employee

bacancy google review 4.6
bacancy google review
bacancy clutch review 4.8
bacancy clutch review
bacancy goodfirms review 4.8
bacancy goodfirms review
iso
  • Bacancy Behance
  • Bacancy Pinterest

Copyright © 2026 BACANCY SERVICES PRIVATE LIMITED All rights reserved.