2016-08-27 10 views
0

私は自分のアプリのカスタムカメラ機能を作っているが、アプリから出て戻ってくるとカメラはフリーズする。これをどうすれば解決できますか?私はアプリに戻ったときにカメラがフリーズする(Obj-C)

ユーザーがアプリをもう一度開いたときに、カメラを再開して、アプリを閉じてもう一度開く必要はありません。

コード:

AVCaptureSession *session; 
AVCaptureStillImageOutput *stillImageOutput; 

- (void)viewWillAppear:(BOOL)animated 
{ 
    session = [[AVCaptureSession alloc] init]; 
    [session setSessionPreset:AVCaptureSessionPresetPhoto]; 

    AVCaptureDevice *inputDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo]; 
    NSError *error; 
    AVCaptureDeviceInput *deviceInput = [AVCaptureDeviceInput deviceInputWithDevice:inputDevice error:&error]; 

    if ([session canAddInput:deviceInput]) { 
     [session addInput:deviceInput]; 
    } 

    AVCaptureVideoPreviewLayer *previewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:session]; 
    [previewLayer setVideoGravity:AVLayerVideoGravityResizeAspectFill]; 
    CALayer *rootLayer = [[self view] layer]; 
    [rootLayer setMasksToBounds:YES]; 
    CGRect frame = frameForCapture.frame; 

    [previewLayer setFrame:frame]; 
    [rootLayer insertSublayer:previewLayer atIndex:0]; 

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

    [session addOutput:stillImageOutput]; 
    [session startRunning]; 

    crossButton.hidden = YES; 
} 

- (IBAction)takePhoto:(id)sender 
{ 
    AVCaptureConnection *videoConnection = nil; 

    for (AVCaptureConnection *connection in stillImageOutput.connections) { 

     for (AVCaptureInputPort *port in [connection inputPorts]) { 

      if ([[port mediaType] isEqual:AVMediaTypeVideo]) { 
       videoConnection = connection; 
       crossButton.hidden = NO; 
       cameraButton.hidden = YES; 
       break; 

      } 

     } 

    } 

    [stillImageOutput captureStillImageAsynchronouslyFromConnection:videoConnection completionHandler:^(CMSampleBufferRef imageDataSampleBuffer, NSError *error) { 

     if (imageDataSampleBuffer != NULL) { 

      NSData *imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer]; 
      UIImage *image = [UIImage imageWithData:imageData]; 
      imageView.image = image; 

     } 
    }]; 
} 

答えて

1

おそらく、あなたのアプリケーションにカメラを設定するには、viewWillAppearまたはviewDidAppearメソッドを使用しています。

使用viewDidLoadカメラを設定する方法は、ビューコントローラがビュー階層をロードする必要があるときはいつでも呼び出されます。

理由:アプリが同じviewControllerに戻って移動するたびに毎回呼ばれる方法viewDidAppearviewWillAppear

関連する問題