Search code examples
iosiphoneswiftcontrol-center

Swift/iOS - Is it possible to run iOS features from Control Center directly from the App?


I want to find out is it possible to run iOS Control Center features, for example screen recording or flashlight directly from the App? if yes, how?


Solution

  • Use this below code to use Flashlight,

    func flashlight() {
        let flashLight: AVCaptureDevice? = AVCaptureDevice.default(for: .video)
        if flashLight?.isTorchAvailable() && flashLight?.isTorchModeSupported(.on) {
            let success: Bool? = try? flashLight?.lockForConfiguration()
            if success ?? false {
                if flashLight?.isTorchActive() != nil {
                    flashLight?.torchMode = .off
                }
                else {
                    flashLight?.torchMode = .on
                }
                flashLight?.unlockForConfiguration()
            }
        }
    }
    

    From iOS 9, screen recording will look like ReplayKit is available to greatly simplify this.

    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)
    }
    

    For more information visit this link: https://developer.apple.com/reference/replaykit