如何在iOS应用最小化后拍照?

3

当iOS应用程序最小化时,如何从相机拍照?
(即在applicationDidEnterBackground: / applicationWillResignActive:之后)

AppDelegate.m:(感谢链接)

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{

    //To make the code block asynchronous
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

        //### background task starts
        NSLog(@"Running in the background\n");
        while(TRUE)
        {
            printf("Called"); //////Work fine

            [self.window.rootViewController captureNow]; /////Capture picture!

            [NSThread sleepForTimeInterval: 10.0]; //wait for 10 sec
        }
    });

    return YES;
}

OurViewController.m: (thank you link)

-(IBAction)captureNow {

    AVCaptureConnection *videoConnection = nil;
    for (AVCaptureConnection *connection in _stillImageOutput.connections)
    {
        for (AVCaptureInputPort *port in [connection inputPorts])
        {
            if ([[port mediaType] isEqual:AVMediaTypeVideo] )
            {
                videoConnection = connection;
                break;
            }
        }
        if (videoConnection)
        {
            break;
        }
    }

    NSLog(@"about to request a capture from: %@", _stillImageOutput);
    [_stillImageOutput captureStillImageAsynchronouslyFromConnection:videoConnection completionHandler: ^(CMSampleBufferRef imageSampleBuffer, NSError *error)
     {
         CFDictionaryRef exifAttachments = CMGetAttachment( imageSampleBuffer, kCGImagePropertyExifDictionary, NULL);

         if (error)
         {
             NSLog(@"ERROR = %@", error); ///// Error!
         }

         NSData *imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageSampleBuffer]; ////SIGABRT, cause imageSampleBuffer is nil
         UIImage *image = [[UIImage alloc] initWithData:imageData];

         UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);

         [image release];
     }];
}

这段代码在应用程序处于活动状态时可以正常工作,但是当应用程序最小化时会出现错误(SIGABRT)。

也许有其他的库可以胜任这项任务?


当应用在后台运行时,您无法访问相机。可能有一些绕过私有API的越狱应用程序的方法,但是您将永远无法获得应用商店的批准。 - Ben Swanson
https://dev59.com/bGgu5IYBdhLWcg3wxZtM - vikingosegundo
1个回答

5

出于隐私原因,当您的应用程序在后台运行时,不允许访问摄像头。

为什么?

好吧,我很高兴你问了。接下来是故事时间!


鲍勃是一位在美国国家安全局工作的人,他正在开发超级秘密的控制猴子的鲨鱼。为什么?他不能说。

有一天,鲍勃在iPhone上下载了一个名为 John's Secret Stealer 的应用程序。鲍勃没有读过应用程序标题。

由于鲍勃非常健忘,有一天他忘记把手机放在工作外面的储物柜里。当他站在超级秘密鲨鱼配方上时,他感到口袋里有手机,并把它拿了出来。手机震动了,因为他刚收到一条短信。

就在那一刻, John's Secret Stealer 使用鲍勃手机的后置摄像头拍了一张照片,将其发送到John的服务器,而鲍勃却毫不知情。

第二天,整个世界都知道了控制鲨鱼的秘密项目。


这是一个极端的例子,但这是规则的原则。苹果的政策是用户始终处于控制之下,以避免像鲍勃一样的情况发生。


1
情节反转!Bob已经认识John并在远处观察他。 - John Riselvato

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接