-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLFMCameraViewController.m
More file actions
757 lines (648 loc) · 33.5 KB
/
LFMCameraViewController.m
File metadata and controls
757 lines (648 loc) · 33.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
//
// AFECameraViewController.m
// AVFoundationExample
//
// Created by Luis Fernando Mata on 27/9/15.
// Copyright © 2015 Luis Fernando Mata. All rights reserved.
//
@import AVFoundation;
@import Photos;
#import "LFMCameraViewController.h"
static void * CapturingStillImageContext = &CapturingStillImageContext;
static void * SessionRunningContext = &SessionRunningContext;
typedef NS_ENUM( NSInteger, AVCamSetupResult ) {
AVCamSetupResultSuccess,
AVCamSetupResultCameraNotAuthorized,
AVCamSetupResultSessionConfigurationFailed
};
@interface LFMCameraViewController () <AVCaptureFileOutputRecordingDelegate>{
enum FlashConfiguration flashConfiguration;
}
// Session management.
@property (nonatomic) dispatch_queue_t sessionQueue; // Communicate with the session and other session objects on this queue.
@property (nonatomic) AVCaptureSession *session;
@property (nonatomic) AVCaptureDeviceInput *videoDeviceInput;
@property (nonatomic) AVCaptureMovieFileOutput *movieFileOutput;
@property (nonatomic) AVCaptureStillImageOutput *stillImageOutput;
// Utilities.
@property (nonatomic) AVCamSetupResult setupResult;
@property (nonatomic, getter=isSessionRunning) BOOL sessionRunning;
@property (nonatomic) UIBackgroundTaskIdentifier backgroundRecordingID;
@property (nonatomic, strong) LFMCameraView *cameraPreview;
@end
@implementation LFMCameraViewController
#pragma mark - View controller methods
- (void)viewDidLoad {
[super viewDidLoad];
// Create the AVCaptureSession
self.session = [[AVCaptureSession alloc] init];
//Set flash enum
flashConfiguration = LFMFlashConfigurationAutomatic;
//Communicate with the session and other object on the queue
self.sessionQueue = dispatch_queue_create("session queue", DISPATCH_QUEUE_SERIAL);
self.setupResult = AVCamSetupResultSuccess;
// Check video authorization status. Video access is required and audio access is optional.
// If audio access is denied, audio is not recorded during movie recording.
switch ( [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo] )
{
case AVAuthorizationStatusAuthorized:
{
// The user has previously granted access to the camera.
break;
}
case AVAuthorizationStatusNotDetermined:
{
// The user has not yet been presented with the option to grant video access.
// We suspend the session queue to delay session setup until the access request has completed to avoid
// asking the user for audio access if video access is denied.
// Note that audio access will be implicitly requested when we create an AVCaptureDeviceInput for audio during session setup.
dispatch_suspend( self.sessionQueue );
[AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^( BOOL granted ) {
if ( ! granted ) {
self.setupResult = AVCamSetupResultCameraNotAuthorized;
}
dispatch_resume( self.sessionQueue );
}];
break;
}
default:
{
// The user has previously denied access.
self.setupResult = AVCamSetupResultCameraNotAuthorized;
break;
}
}
dispatch_async( self.sessionQueue, ^{
[self setUpCaptureSession];
});
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
dispatch_async( self.sessionQueue, ^{
switch ( self.setupResult )
{
case AVCamSetupResultSuccess:
{
// Only setup observers and start the session running if setup succeeded.
[self addObservers];
[self.session startRunning];
self.sessionRunning = self.session.isRunning;
break;
}
case AVCamSetupResultCameraNotAuthorized:
{
dispatch_async( dispatch_get_main_queue(), ^{
NSString *message = NSLocalizedString( @"AVCam doesn't have permission to use the camera, please change privacy settings", @"Alert message when the user has denied access to the camera" );
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"AVCam" message:message preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString( @"OK", @"Alert OK button" ) style:UIAlertActionStyleCancel handler:nil];
[alertController addAction:cancelAction];
// Provide quick access to Settings.
UIAlertAction *settingsAction = [UIAlertAction actionWithTitle:NSLocalizedString( @"Settings", @"Alert button to open Settings" ) style:UIAlertActionStyleDefault handler:^( UIAlertAction *action ) {
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
}];
[alertController addAction:settingsAction];
[self presentViewController:alertController animated:YES completion:nil];
} );
break;
}
case AVCamSetupResultSessionConfigurationFailed:
{
dispatch_async( dispatch_get_main_queue(), ^{
NSString *message = NSLocalizedString( @"Unable to capture media", @"Alert message when something goes wrong during capture session configuration" );
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"AVCam" message:message preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString( @"OK", @"Alert OK button" ) style:UIAlertActionStyleCancel handler:nil];
[alertController addAction:cancelAction];
[self presentViewController:alertController animated:YES completion:nil];
} );
break;
}
}
} );
}
- (void)viewDidDisappear:(BOOL)animated
{
dispatch_async( self.sessionQueue, ^{
if ( self.setupResult == AVCamSetupResultSuccess ) {
[self.session stopRunning];
[self removeObservers];
}
} );
[super viewDidDisappear:animated];
}
- (BOOL)prefersStatusBarHidden
{
return YES;
}
#pragma mark Orientation
- (BOOL)shouldAutorotate
{
// Disable autorotation of the interface when recording is in progress.
return ! self.movieFileOutput.isRecording;
}
- (UIInterfaceOrientationMask)supportedInterfaceOrientations
{
return UIInterfaceOrientationMaskAll;
}
- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator
{
[super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
// Note that the app delegate controls the device orientation notifications required to use the device orientation.
UIDeviceOrientation deviceOrientation = [UIDevice currentDevice].orientation;
if ( UIDeviceOrientationIsPortrait( deviceOrientation ) || UIDeviceOrientationIsLandscape( deviceOrientation ) ) {
AVCaptureVideoPreviewLayer *previewLayer = (AVCaptureVideoPreviewLayer *)self.cameraPreview.layer;
previewLayer.connection.videoOrientation = (AVCaptureVideoOrientation)deviceOrientation;
}
}
#pragma mark KVO and Notifications
- (void)addObservers
{
[self.session addObserver:self forKeyPath:@"running" options:NSKeyValueObservingOptionNew context:SessionRunningContext];
[self.stillImageOutput addObserver:self forKeyPath:@"capturingStillImage" options:NSKeyValueObservingOptionNew context:CapturingStillImageContext];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(subjectAreaDidChange:) name:AVCaptureDeviceSubjectAreaDidChangeNotification object:self.videoDeviceInput.device];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(sessionRuntimeError:) name:AVCaptureSessionRuntimeErrorNotification object:self.session];
// A session can only run when the app is full screen. It will be interrupted in a multi-app layout, introduced in iOS 9,
// see also the documentation of AVCaptureSessionInterruptionReason. Add observers to handle these session interruptions
// and show a preview is paused message. See the documentation of AVCaptureSessionWasInterruptedNotification for other
// interruption reasons.
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(sessionWasInterrupted:) name:AVCaptureSessionWasInterruptedNotification object:self.session];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(sessionInterruptionEnded:) name:AVCaptureSessionInterruptionEndedNotification object:self.session];
}
- (void)removeObservers
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
[self.session removeObserver:self forKeyPath:@"running" context:SessionRunningContext];
[self.stillImageOutput removeObserver:self forKeyPath:@"capturingStillImage" context:CapturingStillImageContext];
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
if ( context == CapturingStillImageContext ) {
BOOL isCapturingStillImage = [change[NSKeyValueChangeNewKey] boolValue];
if ( isCapturingStillImage ) {
dispatch_async( dispatch_get_main_queue(), ^{
/*self.previewView.layer.opacity = 0.0;*/
[UIView animateWithDuration:0.25 animations:^{
//self.previewView.layer.opacity = 1.0;
}];
} );
}
}
else if ( context == SessionRunningContext ) {
//BOOL isSessionRunning = [change[NSKeyValueChangeNewKey] boolValue];
dispatch_async( dispatch_get_main_queue(), ^{
// Only enable the ability to change camera if the device has more than one camera.
/*self.cameraButton.enabled = isSessionRunning && ( [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo].count > 1 );
self.recordButton.enabled = isSessionRunning;
self.stillButton.enabled = isSessionRunning;*/
} );
}
else {
[super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
}
}
- (void)subjectAreaDidChange:(NSNotification *)notification
{
CGPoint devicePoint = CGPointMake( 0.5, 0.5 );
[self focusWithMode:AVCaptureFocusModeContinuousAutoFocus exposeWithMode:AVCaptureExposureModeContinuousAutoExposure atDevicePoint:devicePoint monitorSubjectAreaChange:NO];
}
- (void)sessionRuntimeError:(NSNotification *)notification
{
NSError *error = notification.userInfo[AVCaptureSessionErrorKey];
NSLog( @"Capture session runtime error: %@", error );
// Automatically try to restart the session running if media services were reset and the last start running succeeded.
// Otherwise, enable the user to try to resume the session running.
if ( error.code == AVErrorMediaServicesWereReset ) {
dispatch_async( self.sessionQueue, ^{
if ( self.isSessionRunning ) {
[self.session startRunning];
self.sessionRunning = self.session.isRunning;
}
else {
dispatch_async( dispatch_get_main_queue(), ^{
//self.resumeButton.hidden = NO;
} );
}
} );
}
else {
//self.resumeButton.hidden = NO;
}
}
- (void)sessionWasInterrupted:(NSNotification *)notification
{
// In some scenarios we want to enable the user to resume the session running.
// For example, if music playback is initiated via control center while using AVCam,
// then the user can let AVCam resume the session running, which will stop music playback.
// Note that stopping music playback in control center will not automatically resume the session running.
// Also note that it is not always possible to resume, see -[resumeInterruptedSession:].
}
- (void)sessionInterruptionEnded:(NSNotification *)notification
{
NSLog( @"Capture session interruption ended" );
}
#pragma mark Device Configuration
- (void) setUpCaptureSession{
if ( self.setupResult == AVCamSetupResultSuccess ) {
self.backgroundRecordingID = UIBackgroundTaskInvalid;
NSError *error = nil;
AVCaptureDevice *videoDevice = [LFMCameraViewController deviceWithMediaType:AVMediaTypeVideo preferringPosition:AVCaptureDevicePositionBack];
AVCaptureDeviceInput *videoDeviceInput = [AVCaptureDeviceInput deviceInputWithDevice:videoDevice error:&error];
if ( ! videoDeviceInput ) {
NSLog( @"Could not create video device input: %@", error );
}
[self.session beginConfiguration];
if ( [self.session canAddInput:videoDeviceInput] ) {
[self.session addInput:videoDeviceInput];
self.videoDeviceInput = videoDeviceInput;
}
else {
NSLog( @"Could not add video device input to the session" );
self.setupResult = AVCamSetupResultSessionConfigurationFailed;
}
AVCaptureDevice *audioDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeAudio];
AVCaptureDeviceInput *audioDeviceInput = [AVCaptureDeviceInput deviceInputWithDevice:audioDevice error:&error];
if ( ! audioDeviceInput ) {
NSLog( @"Could not create audio device input: %@", error );
}
if ( [self.session canAddInput:audioDeviceInput] ) {
[self.session addInput:audioDeviceInput];
}
else {
NSLog( @"Could not add audio device input to the session" );
}
AVCaptureMovieFileOutput *movieFileOutput = [[AVCaptureMovieFileOutput alloc] init];
if ( [self.session canAddOutput:movieFileOutput] ) {
[self.session addOutput:movieFileOutput];
AVCaptureConnection *connection = [movieFileOutput connectionWithMediaType:AVMediaTypeVideo];
if ( connection.isVideoStabilizationSupported ) {
connection.preferredVideoStabilizationMode = AVCaptureVideoStabilizationModeAuto;
}
self.movieFileOutput = movieFileOutput;
}
else {
NSLog( @"Could not add movie file output to the session" );
self.setupResult = AVCamSetupResultSessionConfigurationFailed;
}
AVCaptureStillImageOutput *stillImageOutput = [[AVCaptureStillImageOutput alloc] init];
if ( [self.session canAddOutput:stillImageOutput] ) {
stillImageOutput.outputSettings = @{AVVideoCodecKey : AVVideoCodecJPEG};
[self.session addOutput:stillImageOutput];
self.stillImageOutput = stillImageOutput;
}
else {
NSLog( @"Could not add still image output to the session" );
self.setupResult = AVCamSetupResultSessionConfigurationFailed;
}
[self.session commitConfiguration];
}
}
- (void)focusWithMode:(AVCaptureFocusMode)focusMode exposeWithMode:(AVCaptureExposureMode)exposureMode atDevicePoint:(CGPoint)point monitorSubjectAreaChange:(BOOL)monitorSubjectAreaChange
{
dispatch_async([self sessionQueue], ^{
AVCaptureDevice *device = [[self videoDeviceInput] device];
NSError *error = nil;
if ([device lockForConfiguration:&error])
{
if ([device isFocusPointOfInterestSupported] && [device isFocusModeSupported:focusMode])
{
[device setFocusMode:focusMode];
[device setFocusPointOfInterest:point];
}
if ([device isExposurePointOfInterestSupported] && [device isExposureModeSupported:exposureMode])
{
[device setExposureMode:exposureMode];
[device setExposurePointOfInterest:point];
}
[device setSubjectAreaChangeMonitoringEnabled:monitorSubjectAreaChange];
[device unlockForConfiguration];
}
else
{
NSLog(@"%@", error);
}
});
}
+ (void)setFlashMode:(AVCaptureFlashMode)flashMode forDevice:(AVCaptureDevice *)device
{
if ([device hasFlash] && [device isFlashModeSupported:flashMode])
{
NSError *error = nil;
if ([device lockForConfiguration:&error])
{
[device setFlashMode:flashMode];
[device unlockForConfiguration];
}
else
{
NSLog(@"%@", error);
}
}
}
+ (AVCaptureDevice *)deviceWithMediaType:(NSString *)mediaType preferringPosition:(AVCaptureDevicePosition)position
{
NSArray *devices = [AVCaptureDevice devicesWithMediaType:mediaType];
AVCaptureDevice *captureDevice = [devices firstObject];
for (AVCaptureDevice *device in devices)
{
if ([device position] == position)
{
captureDevice = device;
break;
}
}
return captureDevice;
}
- (FlashConfiguration) cameraFlashConfiguration{
return flashConfiguration;
}
- (void) setFlashConfiguration: (FlashConfiguration) newConfiguration{
flashConfiguration = newConfiguration;
}
- (BOOL) isCameraAvailable{
return self.setupResult == AVCamSetupResultSuccess ? YES: NO;
}
#pragma mark - Actions
- (IBAction)resumeInterruptedSession:(id)sender
{
dispatch_async( self.sessionQueue, ^{
// The session might fail to start running, e.g., if a phone or FaceTime call is still using audio or video.
// A failure to start the session running will be communicated via a session runtime error notification.
// To avoid repeatedly failing to start the session running, we only try to restart the session running in the
// session runtime error handler if we aren't trying to resume the session running.
[self.session startRunning];
self.sessionRunning = self.session.isRunning;
if ( ! self.session.isRunning ) {
dispatch_async( dispatch_get_main_queue(), ^{
NSString *message = NSLocalizedString( @"Unable to resume", @"Alert message when unable to resume the session running" );
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"AVCam" message:message preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString( @"OK", @"Alert OK button" ) style:UIAlertActionStyleCancel handler:nil];
[alertController addAction:cancelAction];
[self presentViewController:alertController animated:YES completion:nil];
} );
}
else {
dispatch_async( dispatch_get_main_queue(), ^{
//self.resumeButton.hidden = YES;
} );
}
} );
}
- (void)focusAndExposeTap:(UIGestureRecognizer *)gestureRecognizer{
CGPoint devicePoint = [(AVCaptureVideoPreviewLayer *)[self.cameraPreview layer] captureDevicePointOfInterestForPoint:[gestureRecognizer locationInView:[gestureRecognizer view]]];
[self focusWithMode:AVCaptureFocusModeAutoFocus exposeWithMode:AVCaptureExposureModeAutoExpose atDevicePoint:devicePoint monitorSubjectAreaChange:YES];
}
- (void) setFrontCameraAsDefault{
dispatch_async( self.sessionQueue, ^{
if (self.setupResult == AVCamSetupResultSuccess) {
AVCaptureDevice *currentVideoDevice = self.videoDeviceInput.device;
AVCaptureDevicePosition preferredPosition = AVCaptureDevicePositionFront;
[self changeInputCameraForPreferredPosition:preferredPosition withCurrentDevice:currentVideoDevice];
}
});
}
- (void)changeCamera{
dispatch_async( self.sessionQueue, ^{
if (self.setupResult == AVCamSetupResultSuccess) {
AVCaptureDevice *currentVideoDevice = self.videoDeviceInput.device;
AVCaptureDevicePosition preferredPosition = AVCaptureDevicePositionUnspecified;
AVCaptureDevicePosition currentPosition = currentVideoDevice.position;
switch ( currentPosition )
{
case AVCaptureDevicePositionUnspecified:
case AVCaptureDevicePositionFront:
preferredPosition = AVCaptureDevicePositionBack;
break;
case AVCaptureDevicePositionBack:
preferredPosition = AVCaptureDevicePositionFront;
break;
}
[self changeInputCameraForPreferredPosition:preferredPosition withCurrentDevice:currentVideoDevice];
}
});
}
- (void) changeInputCameraForPreferredPosition: (AVCaptureDevicePosition) preferredPosition withCurrentDevice: (AVCaptureDevice *) currentVideoDevice{
AVCaptureDevice *videoDevice = [LFMCameraViewController deviceWithMediaType:AVMediaTypeVideo preferringPosition:preferredPosition];
AVCaptureDeviceInput *videoDeviceInput = [AVCaptureDeviceInput deviceInputWithDevice:videoDevice error:nil];
[self.session beginConfiguration];
// Remove the existing device input first, since using the front and back camera simultaneously is not supported.
[self.session removeInput:self.videoDeviceInput];
if ( [self.session canAddInput:videoDeviceInput] ) {
[[NSNotificationCenter defaultCenter] removeObserver:self name:AVCaptureDeviceSubjectAreaDidChangeNotification object:currentVideoDevice];
[LFMCameraViewController setFlashMode:AVCaptureFlashModeAuto forDevice:videoDevice];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(subjectAreaDidChange:) name:AVCaptureDeviceSubjectAreaDidChangeNotification object:videoDevice];
[self.session addInput:videoDeviceInput];
self.videoDeviceInput = videoDeviceInput;
}
else {
[self.session addInput:self.videoDeviceInput];
}
AVCaptureConnection *connection = [self.movieFileOutput connectionWithMediaType:AVMediaTypeVideo];
if ( connection.isVideoStabilizationSupported ) {
connection.preferredVideoStabilizationMode = AVCaptureVideoStabilizationModeAuto;
}
[self.session commitConfiguration];
}
#pragma mark Photo actions
- (void) takeStillPictureSavingInImagesWithSuccessBlock: (void (^)(UIImage *cameraImage))success forFailure: (void (^)(NSError *error))failure{
[self takeStillPictureWithSuccessBlock:^(UIImage *cameraImage) {
success(cameraImage);
[self saveImage:cameraImage successBlock:^{
} forFailure:^(NSError *error) {
failure(error);
}];
} forFailure:^(NSError *error) {
failure(error);
}];
}
- (void) takeStillPictureWithSuccessBlock: (void (^)(UIImage *cameraImage))success forFailure: (void (^)(NSError *error))failure{
dispatch_async( self.sessionQueue, ^{
AVCaptureConnection *connection = [self.stillImageOutput connectionWithMediaType:AVMediaTypeVideo];
AVCaptureVideoPreviewLayer *previewLayer = (AVCaptureVideoPreviewLayer *)self.cameraPreview.layer;
// Update the orientation on the still image output video connection before capturing.
connection.videoOrientation = previewLayer.connection.videoOrientation;
// Flash set by default it would be Auto, but you can change this
AVCaptureFlashMode flashMode;
switch (flashConfiguration) {
case LFMFlashConfigurationAutomatic:
flashMode = AVCaptureFlashModeAuto;
break;
case LFMFlashConfigurationAlways:
flashMode = AVCaptureFlashModeOn;
break;
case LFMFlashConfigurationDeactivated:
flashMode = AVCaptureFlashModeOff;
break;
default:
break;
}
[LFMCameraViewController setFlashMode:flashMode forDevice:self.videoDeviceInput.device];
// Capture a still image.
[self.stillImageOutput captureStillImageAsynchronouslyFromConnection:connection completionHandler:^( CMSampleBufferRef imageDataSampleBuffer, NSError *error ) {
[self runStillImageCaptureAnimation];
if ( imageDataSampleBuffer ) {
// The sample buffer is not retained. Create image data before saving the still image to the photo library asynchronously.
NSData *imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer];
UIImage *imageTaken = [UIImage imageWithData:imageData];
success(imageTaken);
}
else {
failure(error);
}
}];
} );
}
#pragma mark Video actions
- (BOOL) isCameraRecording{
return self.movieFileOutput.isRecording;
}
- (void)toggleMovieRecording{
// Disable the Camera button until recording finishes, and disable the Record button until recording starts or finishes. See the
// AVCaptureFileOutputRecordingDelegate methods.
dispatch_async( self.sessionQueue, ^{
if ( ! self.movieFileOutput.isRecording ) {
if ( [UIDevice currentDevice].isMultitaskingSupported ) {
// Setup background task. This is needed because the -[captureOutput:didFinishRecordingToOutputFileAtURL:fromConnections:error:]
// callback is not received until AVCam returns to the foreground unless you request background execution time.
// This also ensures that there will be time to write the file to the photo library when AVCam is backgrounded.
// To conclude this background execution, -endBackgroundTask is called in
// -[captureOutput:didFinishRecordingToOutputFileAtURL:fromConnections:error:] after the recorded file has been saved.
self.backgroundRecordingID = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:nil];
}
// Update the orientation on the movie file output video connection before starting recording.
AVCaptureConnection *connection = [self.movieFileOutput connectionWithMediaType:AVMediaTypeVideo];
AVCaptureVideoPreviewLayer *previewLayer = (AVCaptureVideoPreviewLayer *)self.cameraPreview.layer;
connection.videoOrientation = previewLayer.connection.videoOrientation;
// Turn OFF flash for video recording.
[LFMCameraViewController setFlashMode:AVCaptureFlashModeOff forDevice:self.videoDeviceInput.device];
// Start recording to a temporary file.
NSString *outputFileName = [NSProcessInfo processInfo].globallyUniqueString;
NSString *outputFilePath = [NSTemporaryDirectory() stringByAppendingPathComponent:[outputFileName stringByAppendingPathExtension:@"mov"]];
[self.movieFileOutput startRecordingToOutputFileURL:[NSURL fileURLWithPath:outputFilePath] recordingDelegate:self];
}
else {
[self.movieFileOutput stopRecording];
}
} );
}
#pragma mark - Save files
- (void) saveImage: (UIImage *) image successBlock: (void (^)(void)) successBlock forFailure: (void (^)(NSError *error))failure{
NSData *imageData = UIImageJPEGRepresentation(image, 0.7);
[PHPhotoLibrary requestAuthorization:^( PHAuthorizationStatus status ) {
if ( status == PHAuthorizationStatusAuthorized ) {
// To preserve the metadata, we create an asset from the JPEG NSData representation.
// Note that creating an asset from a UIImage discards the metadata.
// In iOS 9, we can use -[PHAssetCreationRequest addResourceWithType:data:options].
// In iOS 8, we save the image to a temporary file and use +[PHAssetChangeRequest creationRequestForAssetFromImageAtFileURL:].
if ( [PHAssetCreationRequest class] ) {
[[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
[[PHAssetCreationRequest creationRequestForAsset] addResourceWithType:PHAssetResourceTypePhoto data:imageData options:nil];
successBlock();
} completionHandler:^( BOOL success, NSError *error ) {
if ( ! success ) {
failure(error);
}
}];
}
else {
NSString *temporaryFileName = [NSProcessInfo processInfo].globallyUniqueString;
NSString *temporaryFilePath = [NSTemporaryDirectory() stringByAppendingPathComponent:[temporaryFileName stringByAppendingPathExtension:@"jpg"]];
NSURL *temporaryFileURL = [NSURL fileURLWithPath:temporaryFilePath];
[[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
NSError *error = nil;
[imageData writeToURL:temporaryFileURL options:NSDataWritingAtomic error:&error];
if ( error ) {
failure(error);
}
else {
[PHAssetChangeRequest creationRequestForAssetFromImageAtFileURL:temporaryFileURL];
}
} completionHandler:^( BOOL success, NSError *error ) {
if ( ! success ) {
failure(error);
}else{
successBlock();
}
// Delete the temporary file.
[[NSFileManager defaultManager] removeItemAtURL:temporaryFileURL error:nil];
}];
}
}
}];
}
#pragma mark File Output Recording Delegate
- (void)captureOutput:(AVCaptureFileOutput *)captureOutput didFinishRecordingToOutputFileAtURL:(NSURL *)outputFileURL fromConnections:(NSArray *)connections error:(NSError *)error{
// Note that currentBackgroundRecordingID is used to end the background task associated with this recording.
// This allows a new recording to be started, associated with a new UIBackgroundTaskIdentifier, once the movie file output's isRecording property
// is back to NO — which happens sometime after this method returns.
// Note: Since we use a unique file path for each recording, a new recording will not overwrite a recording currently being saved.
UIBackgroundTaskIdentifier currentBackgroundRecordingID = self.backgroundRecordingID;
self.backgroundRecordingID = UIBackgroundTaskInvalid;
dispatch_block_t cleanup = ^{
[[NSFileManager defaultManager] removeItemAtURL:outputFileURL error:nil];
if ( currentBackgroundRecordingID != UIBackgroundTaskInvalid ) {
[[UIApplication sharedApplication] endBackgroundTask:currentBackgroundRecordingID];
}
};
BOOL success = YES;
if ( error ) {
NSLog( @"Movie file finishing error: %@", error );
success = [error.userInfo[AVErrorRecordingSuccessfullyFinishedKey] boolValue];
}
if ( success ) {
// Check authorization status.
[PHPhotoLibrary requestAuthorization:^( PHAuthorizationStatus status ) {
if ( status == PHAuthorizationStatusAuthorized ) {
// Save the movie file to the photo library and cleanup.
[[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
// In iOS 9 and later, it's possible to move the file into the photo library without duplicating the file data.
// This avoids using double the disk space during save, which can make a difference on devices with limited free disk space.
if ( [PHAssetResourceCreationOptions class] ) {
PHAssetResourceCreationOptions *options = [[PHAssetResourceCreationOptions alloc] init];
options.shouldMoveFile = YES;
PHAssetCreationRequest *changeRequest = [PHAssetCreationRequest creationRequestForAsset];
[changeRequest addResourceWithType:PHAssetResourceTypeVideo fileURL:outputFileURL options:options];
}
else {
[PHAssetChangeRequest creationRequestForAssetFromVideoAtFileURL:outputFileURL];
}
} completionHandler:^( BOOL success, NSError *error ) {
if ( ! success ) {
NSLog( @"Could not save movie to photo library: %@", error );
}
cleanup();
}];
}
else {
cleanup();
}
}];
}
else {
cleanup();
}
}
#pragma mark - UI
- (void)runStillImageCaptureAnimation
{
dispatch_async(dispatch_get_main_queue(), ^{
[[self.cameraPreview layer] setOpacity:0.0];
[UIView animateWithDuration:.25 animations:^{
[[self.cameraPreview layer] setOpacity:1.0];
}];
});
}
- (void)setCameraView: (LFMCameraView *) cameraView{
dispatch_async(dispatch_get_main_queue(), ^{
self.cameraPreview = cameraView;
[cameraView setSession:self.session];
[self.cameraPreview setSession:self.session];
UIInterfaceOrientation statusBarOrientation = [UIApplication sharedApplication].statusBarOrientation;
AVCaptureVideoOrientation initialVideoOrientation = AVCaptureVideoOrientationPortrait;
if ( statusBarOrientation != UIInterfaceOrientationUnknown ) {
initialVideoOrientation = (AVCaptureVideoOrientation)statusBarOrientation;
}
AVCaptureVideoPreviewLayer *previewLayer = (AVCaptureVideoPreviewLayer *)self.cameraPreview.layer;
previewLayer.connection.videoOrientation = initialVideoOrientation;
});
}
@end