3

I want to scan QR Code in Share Extension, the codes below can run correctly in normal iOS application

AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];

NSError *error;
AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:device error:&error];
if (error != nil) {
    NSLog(@"no camera");
    return;
}

AVCaptureMetadataOutput *output = [[AVCaptureMetadataOutput alloc] init];
[output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];

self.session = [[AVCaptureSession alloc] init];
[self.session addInput:input];
[self.session addOutput:output];

output.metadataObjectTypes = [NSArray arrayWithObject:AVMetadataObjectTypeQRCode];

self.preview = [AVCaptureVideoPreviewLayer layerWithSession:self.session];
CGRect rect = CGRectMake(50, 50, 300, 600);
self.preview.frame = rect;

[self.view.layer insertSublayer:self.preview atIndex:0];

[self setRuntimeErrorHandlingObserver:[[NSNotificationCenter defaultCenter] addObserverForName:AVCaptureSessionRuntimeErrorNotification object:[self session] queue:nil usingBlock:^(NSNotification *note) {
    NSLog(@"session runtime error: %@", note);
}]];
[self.session startRunning];

But when I run this codes in Share Extension, it shows error message:

NSConcreteNotification 0x174244a70 {name = AVCaptureSessionRuntimeErrorNotification; object = <AVCaptureSession: 0x17400a280 [AVCaptureSessionPresetHigh]>; userInfo = {

AVCaptureSessionErrorKey = "Error Domain=AVFoundationErrorDomain Code=-11837 \"Cannot Use (null)\" UserInfo=0x174262500 {NSLocalizedDescription=Cannot Use (null), NSLocalizedFailureReason=(null) may not be used by an app running in the background.}";}}

Does this mean that the Share Extension is running in background, is there any other ways to fix.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Fred Zhang
  • 115
  • 1
  • 2
  • 8

0 Answers0