How to record IOS screen programmatically

Testiphone picture Testiphone · Jul 12, 2016 · Viewed 21k times · Source

Is there any way to record IOS screen programmatically. Means whatever activity you are doing like clicking buttons, Scrolling tableviews.

Even if a video is playing that will be captured again along with some other activity?

Have tried these

  1. https://www.raywenderlich.com/30200/avfoundation-tutorial-adding-overlays-and-animations-to-videos
  2. https://github.com/alskipp/ASScreenRecorder

but with these libraries won't provide quality video. I need quality video.

The issue is that with video playing in the background when i capture screen it does not show smooth video. It shows like one frame of video and then after 3-4 secs 2nd frame and so on. Also quality of video is not good its blurred

Answer

biomiker picture biomiker · Mar 10, 2017

As of iOS 9, it looks like ReplayKit is available to greatly simplify this.

https://developer.apple.com/reference/replaykit

https://code.tutsplus.com/tutorials/ios-9-an-introduction-to-replaykit--cms-25458

Update: This may be less relevant now that iOS 11 has a built-in screen recorder, but the following Swift 3 code worked for me:

import ReplayKit

@IBAction func toggleRecording(_ sender: UIBarButtonItem) {
    let r = RPScreenRecorder.shared()

    guard r.isAvailable else {
        print("ReplayKit unavailable")
        return
    }
    
    if r.isRecording {
        self.stopRecording(sender, r)
        
    }
    else {
        self.startRecording(sender, r)
    }
}

func startRecording(_ sender: UIBarButtonItem, _ r: RPScreenRecorder) {
    
    r.startRecording(handler: { (error: Error?) -> Void in
        if error == nil { // Recording has started
            sender.title = "Stop"
        } else {
            // Handle error
            print(error?.localizedDescription ?? "Unknown error")
        }
    })
}

func stopRecording(_ sender: UIBarButtonItem, _ r: RPScreenRecorder) {
    r.stopRecording( handler: { previewViewController, error in

        sender.title = "Record"
        
        if let pvc = previewViewController {

            if UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiom.pad {
                pvc.modalPresentationStyle = UIModalPresentationStyle.popover
                pvc.popoverPresentationController?.sourceRect = CGRect.zero
                pvc.popoverPresentationController?.sourceView = self.view
            }

            pvc.previewControllerDelegate = self
            self.present(pvc, animated: true, completion: nil)
        }
        else if let error = error {
            print(error.localizedDescription)
        }
        
    })
}

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