AVCaptureVideoPreviewLayer 不显示

AVCaptureVideoPreviewLayer not showing

目标是简单地显示来自网络摄像头的实时视频输入。

该代码是从 Apple 的一个示例中提炼出来的,它似乎至少可以部分工作,因为 运行ning 时相机旁边的 LED 会亮起。

我从情节提要中的视图按住 trl 键并拖动到界面中的出口 属性,它现在作为参考出口连接,但没有任何显示,甚至没有设置黑色背景颜色。

知道我哪里出错了吗?

感谢您的帮助

编辑: 实际上,如果我在 [previewViewLayer addSublayer:self.previewLayer]; 行设置断点并在调试器中继续到 运行,它会按预期工作。必须有某种时间问题。

接口:

@property (retain) AVCaptureDevice *videoDevice;
@property (retain) AVCaptureDeviceInput *videoDeviceInput;
@property (retain) AVCaptureSession *session;
@property (retain) AVCaptureVideoPreviewLayer *previewLayer;

@property (assign) IBOutlet NSView *previewView;

实施:

- (void)viewDidLoad {
    [super viewDidLoad];
    [self getDevice];
    [self initSession];
}

- (void)initSession {
    // Create a capture session
//    self.session = [[AVCaptureSession alloc] init];
    [self setSession:[[AVCaptureSession alloc] init]];

    // Attach preview to session
    CALayer *previewViewLayer = [self.previewView layer];
    [previewViewLayer setBackgroundColor:CGColorGetConstantColor(kCGColorBlack)];
    self.previewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:self.session];
    [self.previewLayer setFrame:[previewViewLayer bounds]];
    [self.previewLayer setAutoresizingMask:kCALayerWidthSizable | kCALayerHeightSizable];
    [previewViewLayer addSublayer:self.previewLayer];

    // Start the session
    [self.session startRunning];

    // Create a device input for the device and add it to the session
    NSError *error = nil;
    AVCaptureDeviceInput *newVideoDeviceInput = [AVCaptureDeviceInput deviceInputWithDevice:self.videoDevice error:&error];

    [self.session addInput:newVideoDeviceInput];
    self.videoDeviceInput = newVideoDeviceInput;

    [self.session commitConfiguration];
}

- (void)getDevice {
    NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];

    for (AVCaptureDevice *device in devices) {

        NSLog(@"Device name: %@", [device localizedName]);        
        self.videoDevice = device;
    }
}

已解决:

[self initSession];- (void)viewDidLoad移动到- (void)viewDidLayout

更新: 我 运行 后来遇到了 - (void)viewDidLayout 的更多问题,所以最终我搬到了 - (void)viewDidAppear