Swift version: 5.10
ReplayKit is one of many useful social media features built into iOS, and it's trivial to add to your projects. What's more, it's not just for games – you can record any kind of app just fine. I should add, though, that the recording quality is fairly low, so it's not worth trying to record fine details.
Below is a complete example of how to use ReplayKit to record the screen. You'll need to add a navigation controller around your view controller because the code uses the right bar button item to start and stop recording, and of course it's down to you to add some interesting user interface that's actually worth recording!
import ReplayKit
import UIKit
class ViewController: UIViewController, RPPreviewViewControllerDelegate {
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Start", style: .plain, target: self, action: #selector(startRecording))
}
@objc func startRecording() {
let recorder = RPScreenRecorder.shared()
recorder.startRecording{ [unowned self] (error) in
if let unwrappedError = error {
print(unwrappedError.localizedDescription)
} else {
self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Stop", style: .plain, target: self, action: #selector(self.stopRecording))
}
}
}
@objc func stopRecording() {
let recorder = RPScreenRecorder.shared()
recorder.stopRecording { [unowned self] (preview, error) in
self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Start", style: .plain, target: self, action: #selector(self.startRecording))
if let unwrappedPreview = preview {
unwrappedPreview.previewControllerDelegate = self
self.present(unwrappedPreview, animated: true)
}
}
}
func previewControllerDidFinish(_ previewController: RPPreviewViewController) {
dismiss(animated: true)
}
}
ReplayKit does three more cool things for you:
SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's all new Paywall Editor allow you to remotely configure your paywall view without any code changes or app updates.
Sponsor Hacking with Swift and reach the world's largest Swift community!
Available from iOS 9.0
This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions.
Link copied to your pasteboard.