I need the iOS camera to take a picture without any input from the user. How would I go about doing this? This is my code so far:
-(void)initCapture{
AVCaptureDeviceInput *newVideoInput = [[AVCaptureDeviceInput alloc] init];
AVCaptureStillImageOutput *newStillImageOutput = [[AVCaptureStillImageOutput alloc] init];
NSDictionary *outputSettings = [[NSDictionary alloc] initWithObjectsAndKeys:
AVVideoCodecJPEG, AVVideoCodecKey,
nil];
[newStillImageOutput setOutputSettings:outputSettings];
AVCaptureSession *newCaptureSession = [[AVCaptureSession alloc] init];
if ([newCaptureSession canAddInput:newVideoInput]) {
[newCaptureSession addInput:newVideoInput];
}
if ([newCaptureSession canAddOutput:newStillImageOutput]) {
[newCaptureSession addOutput:newStillImageOutput];
}
self.stillImageOutput = newStillImageOutput;
}
What else do I need to add and where do I go from here? I don't want to take a video, only a single still image. Also, how would I convert the image into a UIImage afterwards? Thanks
Look at AVCaptureSession on how to take take picture without user input. You will need to add AVCaptureDevice for camera to the session.
You've got an AVCaptureStillImageOutput, stillImageOutput
. Plus you need to have stored your capture session where you can get at it later. Call it self.sess
. Then:
AVCaptureConnection *vc =
[self.stillImageOutput connectionWithMediaType:AVMediaTypeVideo];
[self.sess startRunning];
[self.stillImageOutput captureStillImageAsynchronouslyFromConnection:vc
completionHandler:
^(CMSampleBufferRef buf, NSError *err) {
NSData* data = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:buf];
UIImage* im = [UIImage imageWithData:data];
dispatch_async(dispatch_get_main_queue(), ^{
UIImageView* iv = [[UIImageView alloc] initWithFrame:someframe];
iv.contentMode = UIViewContentModeScaleAspectFit;
iv.image = im;
[self.view addSubview: iv];
[self.iv removeFromSuperview]; // in case we already did this
self.iv = iv;
[self.sess stopRunning];
});
}];
As @Salil says, the apple's official AVFoundation is very useful, take a look at that to understand main concept. Then you can download a sample code to see how to achieve the goal.
Here is the sample code to take still images with a preview layer.
来源:https://stackoverflow.com/questions/22426293/how-to-force-ios-camera-to-take-a-picture-programmatically-using-avfoundation