为什么这段代码有时会起作用,而不是其他代码?

时间:2012-09-17 05:46:10

标签: objective-c camera uiimagepickercontroller avcapturesession

我在我的应用程序中创建了一个“镜像”视图,它使用前置摄像头向用户显示“镜像”。我遇到的问题是我几周没有触及这个代码(当时它确实有效)但现在我再次测试它并且它无法正常工作。代码与以前相同,没有错误出现,故事板中的视图与之前完全相同。我不知道发生了什么,所以我希望这个网站会有所帮助。

这是我的代码:

if([UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceFront]) {
        //If the front camera is available, show the camera


        AVCaptureSession *session = [[AVCaptureSession alloc] init];
        AVCaptureOutput *output = [[AVCaptureStillImageOutput alloc] init];
        [session addOutput:output];

        //Setup camera input
        NSArray *possibleDevices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
        //You could check for front or back camera here, but for simplicity just grab the first device
        AVCaptureDevice *device = [possibleDevices objectAtIndex:1];
        NSError *error = nil;
        // create an input and add it to the session
        AVCaptureDeviceInput* input = [AVCaptureDeviceInput deviceInputWithDevice:device error:&error]; //Handle errors

        //set the session preset
        session.sessionPreset = AVCaptureSessionPresetHigh; //Or other preset supported by the input device
        [session addInput:input];

        AVCaptureVideoPreviewLayer *previewLayer = [AVCaptureVideoPreviewLayer layerWithSession:session];
        //Now you can add this layer to a view of your view controller
        [cameraView.layer addSublayer:previewLayer];
        previewLayer.frame = self.cameraView.bounds;
        [session startRunning];
        if ([session isRunning]) {
            NSLog(@"The session is running");
        }
        if ([session isInterrupted]) {
            NSLog(@"The session has been interupted");
        }

    } else {
        //Tell the user they don't have a front facing camera
    }

先谢谢你。

1 个答案:

答案 0 :(得分:5)

不确定这是否是问题,但代码和评论之间存在不一致。不一致是使用以下代码行:

AVCaptureDevice *device = [possibleDevices objectAtIndex:1];

在上面的评论中,它说:“......为了简单起见,只需抓住第一台设备”。但是,代码正在抓取第二个设备,NSArray从0开始编号。我认为应该更正注释,因为我认为你假设前置摄像头将是阵列中的第二个设备。

如果你假设第一个设备是后置摄像头而第二个设备是前置摄像头,那么这是一个危险的假设。检查作为前置摄像头的设备的possibleDevices列表会更安全,更具前瞻性。

以下代码将使用前置摄像头枚举possibleDevices列表并创建input

// Find the front camera and create an input and add it to the session
AVCaptureDeviceInput* input = nil;

for(AVCaptureDevice *device in possibleDevices) {
    if ([device position] == AVCaptureDevicePositionFront) {
        NSError *error = nil;

        input = [AVCaptureDeviceInput deviceInputWithDevice:device 
                                                      error:&error]; //Handle errors
        break;
    }
}

更新:我刚刚将问题中的代码完全剪切并粘贴到一个简单的项目中,它对我来说很好。我正在看前置摄像头的视频。您可能应该在其他地方查找该问题。首先,我倾向于检查cameraView和相关的图层。