0

i'll post below the 2 section of code of my 2 .swift files:

Master .swift(partial code)

import UIKit
import AVFoundation
import PageMenu
import SwiftyCam




class randomController: SwiftyCamViewController, SwiftyCamViewControllerDelegate, UIImagePickerControllerDelegate,UINavigationControllerDelegate, CAPSPageMenuDelegate, AVCapturePhotoCaptureDelegate   {



    @IBOutlet weak var cameraPreview: UIImageView!
    @IBOutlet weak var backgroundImage: UIImageView!

    let preview: PreviewView = {
        let pv = PreviewView()
        pv.cameraPreviewFrame = cameraPreview.bounds
        return pv
    }()

    @IBAction func cameraButton(_ sender: Any) {




    }


    @IBOutlet weak var backgroundMarrone: UIImageView!

    func askPermission() {
        print("here")
        let cameraPermissionStatus =  AVCaptureDevice.authorizationStatus(forMediaType: AVMediaTypeVideo)

        switch cameraPermissionStatus {
        case .authorized:
            print("Already Authorized")
        case .denied:
            print("denied")

            let alert = UIAlertController(title: "Sorry :(" , message: "But  could you please grant permission for camera within device settings",  preferredStyle: .alert)
            let action = UIAlertAction(title: "Ok", style: .cancel,  handler: nil)
            alert.addAction(action)
            present(alert, animated: true, completion: nil)

        case .restricted:
            print("restricted")
        default:
            AVCaptureDevice.requestAccess(forMediaType: AVMediaTypeVideo, completionHandler: {
                [weak self]
                (granted :Bool) -> Void in

                if granted == true {
                    // User granted
                    print("User granted")
                    DispatchQueue.main.async(){
                        //Do smth that you need in main thread
                    }
                }
                else {
                    // User Rejected
                    print("User Rejected")

                    DispatchQueue.main.async(){
                        let alert = UIAlertController(title: "WHY?" , message:  "Camera it is the main feature of our application", preferredStyle: .alert)
                        let action = UIAlertAction(title: "Ok", style: .cancel, handler: nil)
                        alert.addAction(action)
                        self?.present(alert, animated: true, completion: nil)  
                    } 
                }
            });
        }
    }
    @IBOutlet weak var cameracapture: UIImageView!
    var pageMenu : CAPSPageMenu?



    @IBAction func cameraCaptureButton(_ sender: Any) {
    takePhoto()
}

    var flashButton = UIButton()

        override func viewDidLoad() {
        super.viewDidLoad()
            cameraDelegate = self
                pageMenu?.delegate = self


        var controllerArray : [UIViewController] = []

        backgroundMarrone.frame = CGRect(x: 0, y:(view.frame.maxY/10*5), width: self.view.frame.width, height: self.view.frame.height )

        cameraPreview.frame = CGRect(x: 0, y: 0, width: self.view.frame.width, height: backgroundMarrone.frame.minY  )


            let switchCameraButton = UIButton(frame: CGRect(x: 5, y: cameraPreview.frame.maxY/12*9.8, width: 50, height: 50))
            switchCameraButton.backgroundColor = UIColor(red: 100.0/255.0, green: 39.0/255.0, blue: 87.0/255.0, alpha: 0.0)
            switchCameraButton.addTarget(self, action: #selector(pressButton(button:)), for: .touchUpInside)
            switchCameraButton.setImage(#imageLiteral(resourceName: "btn_reverse_camera copy.png"), for: UIControlState.normal)
            self.view.addSubview(switchCameraButton)

            flashButton = UIButton(frame: CGRect(x: cameraPreview.frame.maxX - 55, y: cameraPreview.frame.maxY/12*9.8, width: 50, height: 50))
            flashButton.backgroundColor = UIColor(red: 100.0/255.0, green: 39.0/255.0, blue: 87.0/255.0, alpha: 0.0)
            flashButton.addTarget(self, action: #selector(pressButton1(button:)), for: .touchUpInside)
            flashButton.setImage(#imageLiteral(resourceName: "btn_flash copy.png"), for: UIControlState.normal)
            self.view.addSubview(flashButton)




        let libraryController : UIViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "libraryController") as! libraryController
            libraryController.title = "Libreria"
            controllerArray.append(libraryController)


            let photoController : UIViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "photoController") as! photoController
            photoController.title = "Foto"
            controllerArray.append(photoController)



        let videoController : UIViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "videoController") as! videoController
        videoController.title = "Video"
        controllerArray.append(videoController)

        let parameters: [CAPSPageMenuOption] = [
            .menuItemSeparatorWidth(0),
            .useMenuLikeSegmentedControl(true),
            .menuItemSeparatorPercentageHeight(0.1),
            .centerMenuItems (true)
        ]

        pageMenu = CAPSPageMenu(viewControllers: controllerArray, frame: CGRect(x: 0, y: cameraPreview.frame.maxY , width: self.view.frame.width, height: view.frame.height ), pageMenuOptions: parameters)

        self.view.addSubview(pageMenu!.view)

        }
var ciaone = false



    override func viewWillAppear(_ animated: Bool) {








        }


    func beginSession(captureDevice : AVCaptureDevice?) {

        ciaone = false



        }






    var a = 0
    func pressButton(button: UIButton) {

        if (a == 0) {
            print("dioschifoso!")
            beginSession(captureDevice: AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo))

            a = 1

        } else {

            beginSession(captureDevice: AVCaptureDevice.defaultDevice(withDeviceType: AVCaptureDeviceType.builtInWideAngleCamera, mediaType: AVMediaTypeVideo, position: AVCaptureDevicePosition.front))


            a = 0

        }
    }
    var flash = 0




    func toggleTorch(on: Bool) {
        //guard let device = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo) else { return }
        /*
        if device.hasTorch {
            do {
                try device.lockForConfiguration()

                if on == true {
                    device.torchMode = .on
                } else {
                    device.torchMode = .off
                }

                device.unlockForConfiguration()
            } catch {
                print("Torch could not be used")
            }
        } else {
            print("Torch is not available")
        }
 */

    }


    func pressButton1(button: UIButton) {
        /*
        if (a == 0) {
                 //toggleTorch(on: true)
            flashButton.setImage(#imageLiteral(resourceName: "btn_flash_off.png"), for: UIControlState.normal)


            a = 1

        } else {


            //toggleTorch(on: false)
            flashButton.setImage(#imageLiteral(resourceName: "btn_flash copy.png"), for: UIControlState.normal)
            a = 0

        }
       */
///////Annullo momentaneamente il codice per switch flash
/*
        let device = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo)
        if (device?.hasTorch)! && (device?.hasFlash)! {
            do {
                try device?.lockForConfiguration()
            } catch {
                // handle error
                return
            }

            device?.focusMode = .continuousAutoFocus
            device?.flashMode = .auto
            if device?.torchMode == .auto {

                device?.torchMode = .on
                device?.flashMode = .on
                flashButton.setImage(#imageLiteral(resourceName: "btn_flash_off.png"), for: UIControlState.normal)
            }
            else if device?.torchMode == .on {
                device?.torchMode = .off
                device?.flashMode = .off
                 flashButton.setImage(#imageLiteral(resourceName: "btn_flash copy.png"), for: UIControlState.normal)
            }
            else {
                device?.torchMode = .auto
                device?.flashMode = .auto
            }

            device?.unlockForConfiguration()
        }
 */

 takePhoto()

 }
    func swiftyCam(_ swiftyCam: SwiftyCamViewController, didTake photo: UIImage) {
        // Called when takePhoto() is called or if a SwiftyCamButton initiates a tap gesture
        // Returns a UIImage captured from the current session
        let newVC = photoViewController(image: photo)
        self.present(newVC, animated: true, completion: nil)


    }






    func capturePicture(){


        }






    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

Secondary .swift (entire code)

import UIKit
import AVFoundation



class PreviewView: UIView {


    override init(frame: CGRect) {
        super.init(frame: frame)
        self.backgroundColor = UIColor.black
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }


    var videoPreviewLayer: AVCaptureVideoPreviewLayer {
        self.videoPreviewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill

        self.videoPreviewLayer.frame = randomController
        return layer as! AVCaptureVideoPreviewLayer

    }

    var session: AVCaptureSession? {
        get {
            return videoPreviewLayer.session
        }
        set {
            videoPreviewLayer.session = newValue
        }
    }

    // MARK: UIView

    override class var layerClass : AnyClass {
        return AVCaptureVideoPreviewLayer.self
    }
}

Now, in my secondary .swift, i need to set the videoPreviewLayer.frame = cameraPreview.bounds .The variable cameraPreview is located in the Master .swift by the way. How can i do this using as little of code as possible? I've already tried to create a let "something" and setting it to =randomController() but an error pops up and tells me "use of an unresolved identifier". Thanks in advance for the help, if i'm unclear about something ask me.

1 Answer 1

1

Change your secondary .swift to:

import UIKit
import AVFoundation



class PreviewView: UIView {


    override init(frame: CGRect) {
        super.init(frame: frame)
        self.backgroundColor = UIColor.black
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    var cameraPreviewFrame: CGRect? {  // declare new variable
        didSet { 
            videoPreviewLayer.frame = cameraPreviewFrame
        }
    }

    var videoPreviewLayer: AVCaptureVideoPreviewLayer {
        self.videoPreviewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
        // this line was deleted: self.videoPreviewLayer.frame = randomController
        return layer as! AVCaptureVideoPreviewLayer

    }

    var session: AVCaptureSession? {
        get {
            return videoPreviewLayer.session
        }
        set {
            videoPreviewLayer.session = newValue
        }
    }

    // MARK: UIView

    override class var layerClass : AnyClass {
        return AVCaptureVideoPreviewLayer.self
    }
}

Update with @Tj3n's suggestion:

And put your Master .swift:

lazy var preview: PreviewView = {
    let pv = PreviewView()
    pv.cameraPreviewFrame = self.cameraPreview.bounds
    return pv
}()
Sign up to request clarification or add additional context in comments.

11 Comments

Thanks for the help, but xcode pops up an error code in the Master .swift after i implemented your code, it tells me "instance member cameraPreview cannot be used on type randomController"
@MattiaGerardi can you update your question with completely Master.swift
Yea sure, gimme a sec
You cant call to instance member cameraPreview on init the PreviewView before randomController fully init, make it lazy var or use didSet to set frame, not really related to the rest of the code
Done, it's a little bit messy , my code, but the important lines are at the top, included yours
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.