from Objective-C to Swift 4 perform selector

263 Views Asked by At

I am new to both Swing and Objective-C and I was trying to work with AVCaptureDevice.

I tried to implement the following code that gives me back a private member of an AVCaptureDevice instance in Objective-C. But I am no able to transfer the same instruction to Swift:

CMIOObjectID connectionID;
AVCaptureDevice *main_cam = (AVCaptureDevice*)[cameras objectAtIndex:0];
connectionID = [main_cam performSelector:NSSelectorFromString(@"connectionID") withObject:nil];

Mainly because the

main_cam.perform(NSSelectorFromString("connectionID"), with: nil) 

in Swift returns an

Unmanaged<AnyObject>  

and does not accept a forced cast to CMIOObjectID.

Is it possible to perform the operation in Swift?

2

There are 2 best solutions below

5
Sweeper On

You can try:

let unmanaged = main_cam.perform(Selector(("connectionID")), with: nil)
if let connectionID = unmanaged?.takeUnretainedValue() as? CMIOObjectID {
    // do your thing
}

You can read about how to use Unmanaged here.

3
Kamil.S On

Using @convention(c)

let selector = NSSelectorFromString("connectionID")
let methodIMP: IMP! = main_cam.method(for: selector)
let result: CMIOObjectID? = unsafeBitCast(methodIMP,to:(@convention(c)(AVCaptureDevice?,Selector)-> CMIOObjectID?).self)(main_cam,selector) 

More details of this approach in my answer here