-1

I'm trying to convert this code to swift, but I keep getting an error in the if-statement, the objective-c code looks like this:

AVCaptureStillImageOutput *stillImageOutPut;
AVCaptureConnection *videoConnection = nil;

for (AVCaptureConnection *connection in stillImageOutput.connections){
      for (AVCaptureInputPort *port in [connection inputPorts]){
          if ([[port mediaType] isEqual:AVMediaTypeVideo]){
          videoConnection = connection;
          break;
           }
      }
}

and my Swift code looks like this:

let stillImageOutPut = AVCaptureStillImageOutput()

let videoConnection:AVCaptureConnection? = nil

        for connection in stillImageOutPut.connections{
            for port in [connection.inputPorts]{
                if
            }
        }

in the if-statement I can't find the .mediaType and the autocomplete says description, getMirror and map. I've tried casting the types in the for-loop in other ways but I just get keep getting errors.

Any suggestions on how to create this for-loop correctly would be appreciated.

martin
  • 1,894
  • 4
  • 37
  • 69

3 Answers3

3

stillImageOutPut.connections is an NSArray in Objective-C, and an Array<AnyObject> in Swift. You'll want to cast it to Array<AVCaptureConnection> in Swift. Similarly, you'll want to cast connection.inputPorts to Array<AVCaptureInputPort>.

let stillImageOutPut = AVCaptureStillImageOutput()

var videoConnection:AVCaptureConnection? = nil

for connection in stillImageOutPut.connections as [AVCaptureConnection] {
    for port in connection.inputPorts as [AVCaptureInputPort] {
        if port.mediaType == AVMediaTypeVideo {
            videoConnection = connection
        }
    }
}
rob mayoff
  • 375,296
  • 67
  • 796
  • 848
1

Lose the brackets in [connection.inputPorts]. This is not Objective-C any longer! Those brackets, in Swift, mean an array, whereas in Objective-C they just signify message-sending. Simply change that line to:

for port in connection.inputPorts {

...and your world will brighten up considerably.

matt
  • 515,959
  • 87
  • 875
  • 1,141
0

Haven't tested this but I think it should work:

for connection in stillImageOutPut.connections{
    for port  in connection.inputPorts as [AVCaptureInputPort]{
        let mediaType = port.mediaType;
    }
}
psobko
  • 1,548
  • 1
  • 14
  • 24