Record Video iOS Tutorial

Apple provides the UIImagePickerController which is an user interface to take videos using the built-in camera of an iOS device. In this tutorial we will take a video which will be saved in the Photo Library of the device. This tutorial is made with Xcode 10 and built for iOS 12.

Open Xcode and create a new Single View App.

For product name, use IOS12RecordVideoTutorial and then fill out the Organization Name and Organization Identifier with your customary values. Enter Swift as Language and choose Next.

Go to the Storyboard and drag two buttons from the Object Library to the main view. Give the buttons a title of "Take Video" and "View Library". The storyboard should look like this.

Hold down the Ctrl key and select both buttons. Click the "Resolve Auto Layout Issues" button on the bottom-right of the Storyboard and select "Add Missing Constraints".

Select the Assistant Editor and make sure the ViewController.swift is visible. Ctrl and drag from the top Button and create the following Action.

Ctrl and drag from the bottom Button and create the following Action.

Go to the ViewController.swift file and add the following line at the top of the file.

import MobileCoreServices

Change the ViewController class declaration line to

class ViewController: UIViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate  {

These delegates are needed to let the ViewController handle the UIImagePickerController delegation. Add the following instance variables

var controller = UIImagePickerController()
let videoFileName = "/video.mp4"

Implement the takeVideo(_:) method

@IBAction func takeVideo(_ sender: Any) {
    // 1 Check if project runs on a device with camera available
    if UIImagePickerController.isSourceTypeAvailable(.camera) {
            
        // 2 Present UIImagePickerController to take video
        controller.sourceType = .camera
        controller.mediaTypes = [kUTTypeMovie as String]
        controller.delegate = self
            
        present(controller, animated: true, completion: nil)
    }
    else {
        print("Camera is not available")
    }
}
  1. The isSourceTypeAvailable method checks if the device supports the Camera sourceType

  2. An ImagePickerController is displayed using the Camera Sourcetype and the Movie mediaType.

Implement the viewLibrary method.

@IBAction func viewLibrary(_ sender: Any) {
    // Display Photo Library
    controller.sourceType = UIImagePickerController.SourceType.photoLibrary
    controller.mediaTypes = [kUTTypeMovie as String]
    controller.delegate = self
        
    present(controller, animated: true, completion: nil)
}

The Photo library is displayed. If the mediaType isn't set to the movie type, the video files will not be displayed. Next, the delegate methods of the UIImagePickerControllerDelegate protocol needs to be implemented.

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
    // 1
    if let selectedVideo:URL = (info[UIImagePickerController.InfoKey.mediaURL] as? URL) {
        // Save video to the main photo album
        let selectorToCall = #selector(ViewController.videoSaved(_:didFinishSavingWithError:context:))
          
        // 2
        UISaveVideoAtPathToSavedPhotosAlbum(selectedVideo.relativePath, self, selectorToCall, nil)
        // Save the video to the app directory
        let videoData = try? Data(contentsOf: selectedVideo)
        let paths = NSSearchPathForDirectoriesInDomains(
            FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)
        let documentsDirectory: URL = URL(fileURLWithPath: paths[0])
        let dataPath = documentsDirectory.appendingPathComponent(videoFileName)
        try! videoData?.write(to: dataPath, options: [])
    }
    // 3
    picker.dismiss(animated: true)
}

The imagePickerController(_:didFinishPickingMediaWithInfo:) method tells the delegate the user picked a movie. The info parameter contains the URL of the picked movie.

  1. The mediatype from the info dictionary is checked if it is a movie type. If this is the case the URL of the video is extracted.

  2. The UISaveVideoAtPathToSavedPhotosAlbum method saves the video into the photo album

  3. The ViewController is dismissed

Implement the videoSave(_:error:context) method.

@objc func videoSaved(_ video: String, didFinishSavingWithError error: NSError!, context: UnsafeMutableRawPointer){
    if let theError = error {
        print("error saving the video = \(theError)")
    } else {
       DispatchQueue.main.async(execute: { () -> Void in
       })
    }
}

This method check if the saving is made succesful, if not an error message is displayed. Build and Run the project. Select the Take Video button and make and choos ea video. This video is made available and can be replayed with the View library button.

You can download the source code of the IOS12RecordVideoTutorial at the ioscreator repository on Github.