6

90%の時間でうまく機能しているカメラプレビューウィンドウがあります。ただし、アプリがバックグラウンドにある場合にアプリに戻ると、プレビューが表示されないことがあります。これは、ビューが読み込まれるときに呼び出すコードです。

- (void) startCamera {

session = [[AVCaptureSession alloc] init];
session.sessionPreset = AVCaptureSessionPresetPhoto;

AVCaptureVideoPreviewLayer *captureVideoPreviewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:session];
captureVideoPreviewLayer.frame = _cameraView.bounds;
[_cameraView.layer addSublayer:captureVideoPreviewLayer];
captureVideoPreviewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
captureVideoPreviewLayer.position=CGPointMake(CGRectGetMidX(_cameraView.bounds), 160);

AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
NSError *error = nil;

AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:device error:&error];
if (!input) {

    NSLog(@"ERROR: %@", error);


    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Important!"
                                                    message:@"Unable to find a camera."
                                                   delegate:nil
                                          cancelButtonTitle:@"Ok"
                                          otherButtonTitles:nil];
    [alert show];
    [alert autorelease];
}

[session addInput:input];

stillImage = [[AVCaptureStillImageOutput alloc] init];
NSDictionary *outputSettings = [[NSDictionary alloc] initWithObjectsAndKeys:AVVideoCodecJPEG , AVVideoCodecKey, nil];
[stillImage setOutputSettings:outputSettings];

[session addOutput:stillImage];
[session startRunning];
}

これが発生した場合は、設定ビューに切り替えて元に戻すことができます。これは問題ありませんが、これは厄介なバグです。プレビューウィンドウは、ストーリーボードのUIViewです。

4

1 に答える 1

9

ビューの読み込み時にキャプチャ セッションを開始しないでください。代わりに、viewWillAppear で開始し、viewWillDissapear で停止します。

アプリがバックグラウンドにあるときに、View Controller が一部のメモリをクリーンアップしているようです。これを念頭に置いてキャプチャ セッションを初期化していることを確認してください。

開始メソッドではなく、プライベート プロパティの getter メソッドでセッションを遅延して割り当てると、この方法でメモリ リークが回避されます。

于 2012-06-04T21:02:38.337 に答える