Swift – Use ReplayKit to record a movie from your app

Today I want to show you how to use the Apple ReplayKit, to record a full-screen video without a status-bar from your app and save it in your library without using external libraries like GPUImages or something like that.

Let’s start!

import ReplayKit

And add the RPScreenRecorder shared instance:

class YourViewController: UIViewController {

    let recorder = RPScreenRecorder.shared()

}

And the delegate callback for finish movie preview:

extension ViewController : RPPreviewViewControllerDelegate {

    func previewControllerDidFinish(_ previewController: RPPreviewViewController) {
        previewController.dismiss(animated: true, completion: nil)
    }

}

Start and stop the recording

You can add a button event, a networking event, whatever you prefer to start and stop your registration. For simplicity I’ve added a Long press gesture recognition and a start-stop method:

func setUpLongPressGestureRecognizer() {
    let longPressGesture = UILongPressGestureRecognizer.init(target: self, action: #selector(longPressAction(sender:)))
    longPressGesture.minimumPressDuration = 0.5
    longPressGesture.delaysTouchesBegan = true

    self.view.addGestureRecognizer(longPressGesture)
}
@objc func longPressAction(sender: UILongPressGestureRecognizer) {
    AudioServicesPlayAlertSound(SystemSoundID(kSystemSoundID_Vibrate))
    self.recording(state: sender.state == .began)
}

I’ve added also the AudioServicesPlayAlertSound just for vibration feedback on start/stop.

Remember to import AudioToolbox if you want to use vibration.

Your recording method becomes like this:

func recording(state: Bool) {
    if state {
        guard recorder.isAvailable else { return }
        recorder.startRecording{ (error) in
            guard error == nil else { return }
        }
    } else {
        recorder.stopRecording { (preview, error) in
            guard let preview = preview else { return }

            preview.modalPresentationStyle = .automatic
            preview.previewControllerDelegate = self

            self.present(preview, animated: true, completion: nil)
        }
    }
}

Whereof course “recorder.startRecording” start recording the movie and “recorder.stopRecording” stop the movie and show a preview with RPPreviewViewController.

The delegate created before, close this preview controller if is showed.

Full code can be downloaded here:

https://github.com/elpsk/ReplayKit

Have fun!

 

Alberto Pasca

Software engineer @ Pirelli & C. S.p.A. with a strong passion for mobile  development, security, and connected things.