Afriyandi Setiawan
Afriyandi Setiawan

Reputation: 456

connectionWithMediaType return nil

I try to implement video feed using glkview but always getting return nil from connectionWithMediaType when i try to rotate the rotation.

here are my setup

override public func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.
    videoFeed = GLKView(frame: self.view.bounds, context: EAGLContext(API: .OpenGLES2))
    videoFeed.autoresizingMask = [UIViewAutoresizing.FlexibleWidth, UIViewAutoresizing.FlexibleHeight]
    videoFeed.translatesAutoresizingMaskIntoConstraints = true
    videoFeed.contentScaleFactor = 1.0
    self.view.addSubview(videoFeed)
    renderContext  = CIContext(EAGLContext: videoFeed.context)
    sessionQueue = dispatch_queue_create("dCamSession", DISPATCH_QUEUE_SERIAL)
    videoFeed.bindDrawable()
}

override public func viewDidAppear(animated: Bool) {
    super.viewDidAppear(animated)
    startSession()
}

func createSession() -> AVCaptureSession {
    let cam = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)
    var input:AVCaptureInput
    do {
        input = try AVCaptureDeviceInput(device: cam)
    } catch _ as NSError {
        print("Cannot Init Cam")
        exit(EXIT_FAILURE)
    }

    //output
    let videoOut = AVCaptureVideoDataOutput()

    videoOut.videoSettings = nil
    videoOut.alwaysDiscardsLateVideoFrames = true
    videoOut.setSampleBufferDelegate(self, queue: sessionQueue)
    //connectionWithMediaType always get nil
    let connection = videoOut.connectionWithMediaType(AVMediaTypeVideo)
    if connection.supportsVideoOrientation {
        connection.videoOrientation = .Portrait
    }

    let session = AVCaptureSession()
    //make sure the stream quality good enough.
    session.sessionPreset = AVCaptureSessionPresetPhoto
    session.addInput(input)
    session.addOutput(videoOut)        
    session.commitConfiguration()

    return session

}

func startSession() {
    if camSession == nil {
        camSession = createSession()
    }
    camSession.startRunning()
}

what did i do wrong?

if i remove videoOrientation than everything normal (but the orientation is wrong).

Never mind, all you need is calling it asynchronously.

Upvotes: 1

Views: 815

Answers (1)

Zoltán
Zoltán

Reputation: 1450

Your problem is that you were trying to access the connection before adding videoOut as an output.

That's also why it works async: by the time you call connectionWithMediaType, your addOutput(videoOut) has already been called.

Upvotes: 7

Related Questions