gpt4 book ai didi

ios - 当我返回应用程序时相机被卡住(Obj-C)

转载 作者:行者123 更新时间:2023-11-29 00:42:14 25 4
gpt4 key购买 nike

我正在为我的应用程序制作自定义相机功能,但是当我从应用程序退出并返回时,相机被卡住。我该如何解决这个问题?

我希望当用户再次打开应用程序时相机能够恢复,而不必关闭应用程序并再次重新打开它。

代码:

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;

}
}];
}

最佳答案

您可能正在使用 viewWillAppearviewDidAppear 方法在应用程序中配置相机。

使用viewDidLoad 方法来配置相机,只要 View Controller 需要加载其 View 层次结构,就会调用一次。

原因:方法 viewDidAppearviewWillAppear 每当应用导航回同一个 viewController 时都会被调用。

关于ios - 当我返回应用程序时相机被卡住(Obj-C),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39178270/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com