Getting started with screen recording with ReplayKit on iOS 11
This year’s WWDC had a lot to offer to us, the developers, right from the brand new additions to the ecosystem like Core ML, ARKit, Drag & Drop etc. to enhancements in existing frameworks. One thing that caught my eye was the enhancment to ReplayKit.
ReplayKit is now not limited just to games but it has been extended throughout the system, meaning - you can record apps, broadcast in-app content, and even stream the whole system (not just the sandboxed environment) to the web.
The possibilities of ReplayKit caught my attention and I thought I could start off with something simple as recording the screen and saving to disk.
With zero prior experience in ReplayKit, I started out by looking at the documentation and found out that there wasn’t much, except for two methods —
startCapture method records the app’s display. Once called, the system presents an alert asking for permission to record the screen.
startCapture emits a
CMSampleBuffer of type
RPSampleBufferType which needs to be converted into a video.
To convert the
CMSampleBuffer to a video,
AVAssetWriter is used along with
Note: Its important to give unique names for the video files because the system will not overwrite an existing file,and
AssetWriter will return with
Here is the tricky part, how will the user call this method and how can we make sure that the trigger to this, say a button, doesn’t get screen-recorded in the process? 🤔
It turns out that,
RPScreenRecorder only captures the elements on the
mainWindow, so any UI Element on a separate window will not be recorded, So its ideal to have a “Stop Recording” button on a separate window.
It’s important to have this button because, this not only allows the user to stop screen recording, but also informs that the screen is being recorded.
Note- It is also important to call the
assetWriter.finishWriting method to write the video files to the disk.
With the video in the documents directory, I can now send this to a web client 😅 🎉
I’ve created a wrapper class to perform all the above mentioned task with a very simple and straight forward API, check it out on Github.