2016-08-27 54 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

也許你正在使用viewWillAppearviewDidAppear方法來配置你的相機在你的應用程序。

使用viewDidLoad方法來配置相機,只要視圖控制器需要加載其視圖層次結構,該方法將被調用一次。

原因:方法viewDidAppearviewWillAppear調用每次只要應用導航回到同一viewController時間。

相關問題