I have a simple C or Objective-C program that prints all connected video devices on MacOS using AVFoundation framework. When I disconnect or connect new video capture device list doesn't get refreshed until I stop program and run it again.
My code looks as follows:
#import <AVFoundation/AVFoundation.h>
#include <stdio.h>
void print_devices() {
NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
for (AVCaptureDevice *device in devices) {
const char *name = [[device localizedName] UTF8String];
fprintf(stderr, "Device: %s\n", name);
}
}
int main() {
print_devices();
sleep(10);
// I connect or disconnect new capture device here via USB
print_devices();
// second print_devices(); displays exact same devices
// as first call to this function.
return 0;
}
My actual program looks a bit different and I call code from Go program but this is minimal reproduction code to see where is the problem. I always get printed same devices until I stop program and start it again then new devices are detected correctly.
Where is the catch or what am I missing here?
You need to run an event loop.
Most likely, AVFoundation only updates its devices list in response to events. You call sleep() in this app. While sleeping, the app receives no notifications. So the devices array is going to be the same before and after the sleep().
If you're using Apple's Foundation/AppKit/UIKit frameworks, you need to write the program in an Apple kind of way. That means using a run loop and timers, instead of sleep();