get a SubLayer with swift2 and Xcode 7

267 views Asked by At

I would save a sublayer. But I can not get a target. I want to save the layer that is displayed on the screen that contains the view of the camera. When I want it back, I get a white image. I concluded that I targeted my male layer when I record in dernnière function. Here is my code:

    @IBOutlet weak var blutEffect: UIVisualEffectView!
    @IBOutlet weak var background: UIView! // vu d'affichage


    var previewLayer = AVCaptureVideoPreviewLayer()
    var captureSession = AVCaptureSession()

    override func viewDidLoad() {
        super.viewDidLoad()     
        camera()
    }

    @IBAction func takePhoto(sender: AnyObject) {
        captureSession.stopRunning()
    }

    func camera () {


        captureSession = AVCaptureSession()
        previewLayer = AVCaptureVideoPreviewLayer()
        var captureDevice : AVCaptureDevice?
        let devices = AVCaptureDevice.devices()
        captureSession.sessionPreset = AVCaptureSessionPresetHigh

        background.layer.sublayers?.removeAll()


        for device in devices {

            if (device.hasMediaType(AVMediaTypeVideo)) { 

                    if(device.position == AVCaptureDevicePosition.Back) { 
                        captureDevice = device as? AVCaptureDevice 
                        if captureDevice != nil { 

                            do {
                                try captureSession.addInput(AVCaptureDeviceInput(device: captureDevice))
                            } catch _ as NSError {
                                print("ERROR")
                            }


                            previewLayer = AVCaptureVideoPreviewLayer(session: captureSession) 
                            self.background.layer.addSublayer(previewLayer) 
                            previewLayer.frame = self.background.layer.frame
                            captureSession.startRunning() 
                        }
                    }
            }  
        }   
    }

    func screenShotMethod() { 
        UIGraphicsBeginImageContext(background.layer.frame.size)
        background.layer.renderInContext(UIGraphicsGetCurrentContext())
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        //Save it to the camera roll
        UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)
    }

Thanks for your help !

0

There are 0 answers