AVFoundation Camera Swift

AVCam-iOSUsingAVFoundationtoCaptureImagesandMovies:
https://github.com/robovm/apple-ios-samples/tree/master/AVCam-iOSUsingAVFoundationtoCaptureImagesandMovies

参考 Apple 的 Objective-C 转化为 Swift 版本。过程中学了不少知识,因没办法 copy-paste,都必须理解相关知识点才行。KVO 、Notification 和多线程等,注释也十分详细。唯一不舒服的就是AVFoundation API 本身没有对 Swift 优化,Swift KVO 也是一个坑。

源码:

https://github.com/gewill/test-projects/tree/master/test%20AVCam

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
//
// JLXCameraViewController.swift
// test AVCam
//
// Created by Will on 4/15/16.
// Copyright © 2016 gewill.org. All rights reserved.
//

import UIKit
import Foundation
import AVFoundation
import Photos
import AssetsLibrary

protocol JLXCameraViewControllerDelegate: NSObjectProtocol {
func cameraViewController(vc: JLXCameraViewController, didFinishCaptureVideoUrl url: NSURL!)
func cameraViewControllerDidCancel(vc: JLXCameraViewController)
}

enum JLXAVCamSetupResult {
case Success
case CameraNotAuthorized
case SessionConfiguratonFailed
}

private var SessionRunningContext = 0

class JLXCameraViewController: UIViewController, AVCaptureFileOutputRecordingDelegate {
@IBOutlet var previewView: JLXPreviewView!

@IBOutlet var cameraUnavailableLabel: UILabel!
@IBOutlet var resumeButton: UIButton!

@IBOutlet var flashButton: UIButton!
@IBOutlet var changeCameraButton: UIButton!
@IBOutlet var cancelButton: UIButton!

@IBOutlet var durationLabel: UILabel!

@IBOutlet var recordButton: UIButton!

var delegate: JLXCameraViewControllerDelegate?

// Session management

// Communicate with the session and other session objects on this queue.
var sessionQueue = dispatch_queue_create("session queue", DISPATCH_QUEUE_SERIAL)
dynamic var session: AVCaptureSession!
var videoDeviceInput: AVCaptureDeviceInput!
var movieFileOutput: AVCaptureMovieFileOutput!

// Utilities
var setupResult: JLXAVCamSetupResult!
var sessionRunning: Bool!
var backgroundRecordingId: UIBackgroundTaskIdentifier!
var durationTimer: NSTimer?
var seconds: Int!
var isRecording = false

// MARK: - life cycle

override func viewDidLoad() {
super.viewDidLoad()

self.setupUI()

self.setupSession()
}

func setupUI() {
// Disable UI. The UI is enabled if and only if the session starts running.
self.changeCameraButton.enabled = false
self.recordButton.enabled = false
self.flashButton.enabled = false

self.resumeButton.setTitle("Tap to resume", forState: .Normal)
self.resumeButton.hidden = true
self.cameraUnavailableLabel.text = "Camera Unavailable"
self.cameraUnavailableLabel.hidden = true

let tapGesture = UITapGestureRecognizer(target: self, action: #selector(JLXCameraViewController.focusAndExposeTap(_:)))
self.previewView.addGestureRecognizer(tapGesture)
}

func setupAuthorization() {
// 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 AVAuthorizationStatus.NotDetermined:
dispatch_suspend(self.sessionQueue)
AVCaptureDevice.requestAccessForMediaType(AVMediaTypeVideo, completionHandler: { (granted) in
if granted == false {
self.setupResult = JLXAVCamSetupResult.CameraNotAuthorized
}
dispatch_resume(self.sessionQueue)
})
case AVAuthorizationStatus.Authorized:
self.setupResult = JLXAVCamSetupResult.Success
default:
self.setupResult = JLXAVCamSetupResult.CameraNotAuthorized
}
}

// Setup the capture session.
// In general it is not safe to mutate an AVCaptureSession or any of its inputs, outputs, or connections from multiple threads at the same time.
// Why not do all of this on the main queue?
// Because -[AVCaptureSession startRunning] is a blocking call which can take a long time. We dispatch session setup to the sessionQueue
// so that the main queue isn't blocked, which keeps the UI responsive.
func setupSession() {
// Create the AVCaptureSession.
self.session = AVCaptureSession()

// Setup the preview view.
self.previewView.setSession(self.session)

self.setupResult = JLXAVCamSetupResult.Success

self.setupAuthorization()

dispatch_async(self.sessionQueue) {
if self.setupResult != JLXAVCamSetupResult.Success {
return
}

self.backgroundRecordingId = UIBackgroundTaskInvalid

let videoDevice: AVCaptureDevice = JLXCameraViewController.deviceWithMediaType(AVMediaTypeVideo, preferringPosition: AVCaptureDevicePosition.Back)

var videoDeviceInput: AVCaptureDeviceInput?
do {
videoDeviceInput = try AVCaptureDeviceInput.init(device: videoDevice)
} catch let error as NSError {
print("Could not create video device input: \(error.debugDescription)")
}

self.session.beginConfiguration()

if self.session.canAddInput(videoDeviceInput) {
self.session.addInput(videoDeviceInput)
self.videoDeviceInput = videoDeviceInput

dispatch_async(dispatch_get_main_queue()) {
// Why are we dispatching this to the main queue?
// Because AVCaptureVideoPreviewLayer is the backing layer for AAPLPreviewView and UIView
// can only be manipulated on the main thread.
// Note: As an exception to the above rule, it is not necessary to serialize video orientation changes
// on the AVCaptureVideoPreviewLayer’s connection with other session manipulation.

// Use the status bar orientation as the initial video orientation. Subsequent orientation changes are handled by
// -[viewWillTransitionToSize:withTransitionCoordinator:].
let orientation = AVCaptureVideoOrientation.LandscapeRight
let previewLayer = self.previewView.layer as! AVCaptureVideoPreviewLayer
previewLayer.connection.videoOrientation = orientation
}
} else {
print("Could not add video device input to the session")
self.setupResult = JLXAVCamSetupResult.SessionConfiguratonFailed
}

// TODO: - test failed
let audioDevice = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeAudio)
let audioDeviceInput: AVCaptureDeviceInput?
do {
audioDeviceInput = try AVCaptureDeviceInput.init(device: audioDevice)
} catch let error as NSError {
print("Could not create audio device input: \(error.debugDescription.debugDescription)")
}

let movieFileOutput = AVCaptureMovieFileOutput()
if self.session.canAddOutput(movieFileOutput) {
self.session.addOutput(movieFileOutput)
let connection = movieFileOutput.connectionWithMediaType(AVMediaTypeVideo)
if #available(iOS 8.0, *) {
if connection.supportsVideoStabilization {
connection.preferredVideoStabilizationMode = .Auto
}
} else {
connection.enablesVideoStabilizationWhenAvailable = true
}

if connection.supportsVideoOrientation {
connection.videoOrientation = AVCaptureVideoOrientation.LandscapeRight
}

self.movieFileOutput = movieFileOutput
} else {
print("Could not add movie file output to the session")
self.setupResult = JLXAVCamSetupResult.SessionConfiguratonFailed
}

self.session.commitConfiguration()
}
}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}

override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)

// response setupResult

dispatch_async(self.sessionQueue) {
if let result = self.setupResult {
switch result {
case .Success:
// Only setup observers and start the session running if setup succeeded.
self.addObservers()
self.session.startRunning()
self.sessionRunning = self.session.running
case .CameraNotAuthorized:
dispatch_async(dispatch_get_main_queue()) {
let title = NSBundle.mainBundle().localizedInfoDictionary!["CFBundleName"] as! String
let message = String.localizedStringWithFormat("AVCam doesn't have permission to use the camera, please change privacy settings", "Alert message when the user has denied access to the camera")
let cancelText = String.localizedStringWithFormat("OK", "Alert OK button")
let settingsText = String.localizedStringWithFormat("Settings", "Alert button to open Settings")
if #available(iOS 8.0, *) {
let alertController = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert)
let cancelAction = UIAlertAction(title: cancelText, style: UIAlertActionStyle.Cancel, handler: nil)
alertController.addAction(cancelAction)
let settingsAction = UIAlertAction(title: settingsText, style: UIAlertActionStyle.Default, handler: { (action) in
UIApplication.sharedApplication().openURL(NSURL(string: UIApplicationOpenSettingsURLString)!)
})
alertController.addAction(settingsAction)
self.presentViewController(alertController, animated: true, completion: nil)
} else {
let alert = UIAlertView(title: title, message: message, delegate: nil, cancelButtonTitle: cancelText, otherButtonTitles: settingsText)
alert.show()
}
}
case .SessionConfiguratonFailed:
let title = NSBundle.mainBundle().localizedInfoDictionary!["CFBundleName"] as! String
let message = String.localizedStringWithFormat("Unable to capture media", "Alert message when something goes wrong during capture session configuration")
let cancelText = String.localizedStringWithFormat("OK", "Alert OK button")
if #available(iOS 8.0, *) {
let alertController = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert)
let cancelAction = UIAlertAction(title: cancelText, style: UIAlertActionStyle.Cancel, handler: nil)
alertController.addAction(cancelAction)
self.presentViewController(alertController, animated: true, completion: nil)
} else {
let alert = UIAlertView(title: title, message: message, delegate: nil, cancelButtonTitle: cancelText)
alert.show()
}
}
}
}
}

override func viewDidDisappear(animated: Bool) {
dispatch_async(self.sessionQueue) {
if self.setupResult == JLXAVCamSetupResult.Success {
self.session.stopRunning()
self.removeObservers()
}
}

super.viewDidDisappear(animated)
}

// MARK: - Orientation

override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
return UIInterfaceOrientationMask.LandscapeRight
}

// MARK: - KVO and Notifications

func addObservers() {
self.session.addObserver(self, forKeyPath: "running", options: NSKeyValueObservingOptions.New, context: &SessionRunningContext)

NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(subjectAreaDidChange(_:)), name: AVCaptureDeviceSubjectAreaDidChangeNotification, object: self.videoDeviceInput.device)
// 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(sessionWatInterruptedEnded(_:)), name: AVCaptureSessionWasInterruptedNotification, object: self.session)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(sessionWatInterruptedEnded(_:)), name: AVCaptureSessionInterruptionEndedNotification, object: self.session)
}

func removeObservers() {
self.session.removeObserver(self, forKeyPath: "running", context: &SessionRunningContext)

NSNotificationCenter.defaultCenter().removeObserver(self)
}

override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String: AnyObject]?, context: UnsafeMutablePointer<Void>) {
if context == &SessionRunningContext {
if let isSessionRunning = change?[NSKeyValueChangeNewKey]?.boolValue where
isSessionRunning == true {
dispatch_async(dispatch_get_main_queue()) {
// Only enable the ability to change camera if the device has more than
// one camera.
self.changeCameraButton.enabled = isSessionRunning && (AVCaptureDevice.devicesWithMediaType(AVMediaTypeVideo).count > 1)
self.recordButton.enabled = isSessionRunning
}
}
} else {
super.observeValueForKeyPath(keyPath, ofObject: object, change: change, context: context)
}
}

func subjectAreaDidChange(notification: NSNotification) {
let devicePoiont = CGPoint(x: 0.5, y: 0.5)
self.focusWithMode(AVCaptureFocusMode.ContinuousAutoFocus, exposureWithMode: AVCaptureExposureMode.ContinuousAutoExposure, atDevicePoint: devicePoiont, monitorSubjectAreaChange: false)
}

func sessionRuntimeError(notification: NSNotification) {
// 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 let error = notification.userInfo?[AVCaptureSessionErrorKey] where
error.code == AVError.MediaServicesWereReset.rawValue {
dispatch_async(self.sessionQueue, {
if self.sessionRunning == true {
self.session.startRunning()
self.sessionRunning = self.session.running
} else {
dispatch_async(dispatch_get_main_queue(), {
self.resumeButton.hidden = false
})
}
})
} else {
self.resumeButton.hidden = false
}
}

func sessionWasInterrupted(notification: NSNotification) {
// 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:].

var showResumeButton = false

// In iOS 9 and later, the userInfo dictionary contains information on why the
// session was interrupted.
if #available(iOS 9.0, *) {
if let reason = notification.userInfo?[AVCaptureSessionInterruptionReasonKey] where reason is Int
{
if (reason as! Int) == AVCaptureSessionInterruptionReason.AudioDeviceInUseByAnotherClient.rawValue || (reason as! Int) == AVCaptureSessionInterruptionReason.VideoDeviceInUseByAnotherClient.rawValue {
showResumeButton = true
} else if (reason as! Int) == AVCaptureSessionInterruptionReason.VideoDeviceNotAvailableWithMultipleForegroundApps.rawValue {
// Simply fade-in a label to inform the user that the camera is
// unavailable.
self.cameraUnavailableLabel.hidden = false
self.cameraUnavailableLabel.alpha = 0
UIView.animateWithDuration(0.25, animations: {
self.cameraUnavailableLabel.alpha = 1
})
}
}
} else {
print("Capture session was interrupted")
showResumeButton = UIApplication.sharedApplication().applicationState == UIApplicationState.Inactive
}

if showResumeButton {
// Simply fade-in a button to enable the user to try to resume the session
// running.
self.resumeButton.hidden = false
self.resumeButton.alpha = 0
UIView.animateWithDuration(0.25, animations: {
self.resumeButton.alpha = 1
})
}
}

func sessionWatInterruptedEnded(notification: NSNotification) {
print("Capture session interruption ended")

// hide buttons with animations
if !self.resumeButton.hidden {
UIView.animateWithDuration(0.25, animations: {
self.resumeButton.alpha = 0
}, completion: { (finished) in
self.resumeButton.hidden = true
})
}

if !self.cameraUnavailableLabel.hidden {
UIView.animateWithDuration(0.25, animations: {
self.cameraUnavailableLabel.alpha = 0
}, completion: { (finished) in
self.cameraUnavailableLabel.hidden = true
})
}
}

// MARK: - Response Actions

@IBAction func resumeButtonClick(sender: AnyObject) {
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.durationTimer = NSTimer(timeInterval: 1.0, target: self, selector: #selector(JLXCameraViewController.refreshDurationLabel), userInfo: nil, repeats: true)
NSRunLoop.currentRunLoop().addTimer(self.durationTimer!, forMode: NSRunLoopCommonModes)
self.durationTimer?.fire()

self.sessionRunning = self.session.running
if !self.session.running {
dispatch_async(dispatch_get_main_queue()) {
let title = NSBundle.mainBundle().localizedInfoDictionary!["CFBundleName"] as! String
let message = String.localizedStringWithFormat("Unable to resume", "Alert message when unable to resume the session running")
let cancelText = String.localizedStringWithFormat("OK", "Alert OK button")
if #available(iOS 8.0, *) {
let alertController = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert)
let cancelAction = UIAlertAction(title: cancelText, style: UIAlertActionStyle.Cancel, handler: nil)
alertController.addAction(cancelAction)
self.presentViewController(alertController, animated: true, completion: nil)
} else {
let alert = UIAlertView(title: title, message: message, delegate: nil, cancelButtonTitle: cancelText)
alert.show()
}
}
} else {
dispatch_async(dispatch_get_main_queue()) {
self.resumeButton.hidden = false
}
}
}
}
@IBAction func recordButtonClick(sender: AnyObject) {
// Disable the Camera button until recording finishes, and disable the Record
// button until recording starts or finishes. See the
// AVCaptureFileOutputRecordingDelegate methods.
self.changeCameraButton.enabled = false
self.recordButton.enabled = false

if self.isRecording == true {
self.durationTimer?.invalidate()
self.durationTimer = nil
self.seconds = 0
self.durationLabel.text = secondsToFormatTimeFull(0)
} else {
self.seconds = 0
self.durationTimer = NSTimer(timeInterval: 1.0, target: self, selector: #selector(JLXCameraViewController.refreshDurationLabel), userInfo: nil, repeats: true)
NSRunLoop.currentRunLoop().addTimer(self.durationTimer!, forMode: NSRunLoopCommonModes)
self.durationTimer?.fire()
}

self.isRecording = !isRecording

dispatch_async(self.sessionQueue) {
if !self.movieFileOutput.recording && UIDevice.currentDevice().multitaskingSupported {
// 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)

// Turn OFF flash for video recording.
JLXCameraViewController.setFlashMode(AVCaptureFlashMode.Off, forDevice: self.videoDeviceInput.device)

// Start recording to a temporary file.
let outputFileName = NSProcessInfo.processInfo().globallyUniqueString
let outputFileUrl = NSURL(fileURLWithPath: NSTemporaryDirectory()).URLByAppendingPathComponent(outputFileName).URLByAppendingPathExtension("mov")
self.movieFileOutput.startRecordingToOutputFileURL(outputFileUrl, recordingDelegate: self)
} else {
self.movieFileOutput.stopRecording()
}
}
}

@IBAction func changeCameraButtonClick(sender: AnyObject) {
self.changeCameraButton.enabled = false
self.recordButton.enabled = false

dispatch_async(self.sessionQueue) {
let currentVideoDivice = self.videoDeviceInput.device
var preferredPosition = AVCaptureDevicePosition.Unspecified
let currentPosition = currentVideoDivice.position

switch currentPosition {
case AVCaptureDevicePosition.Front:
preferredPosition = AVCaptureDevicePosition.Back
case AVCaptureDevicePosition.Back:
preferredPosition = AVCaptureDevicePosition.Front
default:
break
}

let videoDevice = JLXCameraViewController.deviceWithMediaType(AVMediaTypeVideo, preferringPosition: preferredPosition)

var videoDeviceInput: AVCaptureDeviceInput?
do {
videoDeviceInput = try AVCaptureDeviceInput.init(device: videoDevice)
} catch let error as NSError {
print("Could not create video device input: \(error.debugDescription)")
}

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: currentVideoDivice)

JLXCameraViewController.setFlashMode(AVCaptureFlashMode.Auto, forDevice: videoDevice)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(JLXCameraViewController.subjectAreaDidChange(_:)), name: AVCaptureDeviceSubjectAreaDidChangeNotification, object: videoDevice)

self.session.addInput(videoDeviceInput)
self.videoDeviceInput = videoDeviceInput
} else {
self.session.addInput(self.videoDeviceInput)
}

let connection = self.movieFileOutput.connectionWithMediaType(AVMediaTypeVideo)
if connection.supportsVideoStabilization {
if #available(iOS 8.0, *) {
connection.preferredVideoStabilizationMode = .Auto
} else {
connection.enablesVideoStabilizationWhenAvailable = true
}
}

self.session.commitConfiguration()

dispatch_async(dispatch_get_main_queue()) {
self.changeCameraButton.enabled = true
self.recordButton.enabled = true
}
}
}

func focusAndExposeTap(gestureRecognizer: UIGestureRecognizer) {
let devicePoint = (self.previewView.layer as! AVCaptureVideoPreviewLayer).captureDevicePointOfInterestForPoint(gestureRecognizer.locationInView(gestureRecognizer.view))
self.focusWithMode(AVCaptureFocusMode.AutoFocus, exposureWithMode: AVCaptureExposureMode.AutoExpose, atDevicePoint: devicePoint, monitorSubjectAreaChange: true)
}

@IBAction func flashButtonClick(sender: AnyObject) {
// TODO: - should deal while changeCameraButton
}

func refreshDurationLabel() {
seconds = seconds + 1
self.durationLabel.text = secondsToFormatTimeFull(Double(self.seconds))
}

@IBAction func cancelButtonClick(sender: AnyObject) {
delegate?.cameraViewControllerDidCancel(self)
self.dismissViewControllerAnimated(true, completion: nil)
}

// MARK: - File Output Recording Delegate
func captureOutput(captureOutput: AVCaptureFileOutput!, didStartRecordingToOutputFileAtURL fileURL: NSURL!, fromConnections connections: [AnyObject]!) {
// Enable the Record button to let the user stop the recording.
dispatch_async(dispatch_get_main_queue()) {
self.recordButton.enabled = true
self.recordButton.setTitle(String.localizedStringWithFormat("Stop", "Recording button stop title"), forState: .Normal)
}
}

func captureOutput(captureOutput: AVCaptureFileOutput!, didFinishRecordingToOutputFileAtURL outputFileURL: NSURL!, fromConnections connections: [AnyObject]!, error: NSError!) {
// 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.

self.delegate?.cameraViewController(self, didFinishCaptureVideoUrl: outputFileURL)
self.dismissViewControllerAnimated(true, completion: nil)
}

// MARK: - Device Configuration
func focusWithMode(focusMode: AVCaptureFocusMode, exposureWithMode exposureMode: AVCaptureExposureMode, atDevicePoint point: CGPoint, monitorSubjectAreaChange: Bool) {
dispatch_async(self.sessionQueue) {
let device = self.videoDeviceInput.device
do {
try device.lockForConfiguration()
// Setting (focus/exposure)PointOfInterest alone does not initiate a
// (focus/exposure) operation.
// Call -set(Focus/Exposure)Mode: to apply the new point of interest.
if device.focusPointOfInterestSupported && device.isFocusModeSupported(AVCaptureFocusMode.AutoFocus) {
device.focusPointOfInterest = point
device.focusMode = focusMode
}

if device.exposurePointOfInterestSupported && device.isExposureModeSupported(AVCaptureExposureMode.AutoExpose) {
device.exposurePointOfInterest = point
device.exposureMode = exposureMode
}

device.subjectAreaChangeMonitoringEnabled = monitorSubjectAreaChange

device.unlockForConfiguration()
} catch let error as NSError {
print(" \(error.debugDescription)")
}
}
}

class func setFlashMode(flashMode: AVCaptureFlashMode, forDevice device: AVCaptureDevice) {
if device.hasFlash && device.isFlashModeSupported(flashMode) {
do {
try device.lockForConfiguration()
device.flashMode = flashMode
device.unlockForConfiguration()
} catch let error as NSError {
print("Could not lock device for configuration: \(error.debugDescription)")
}
}
}

class func deviceWithMediaType(mediaType: String, preferringPosition position: AVCaptureDevicePosition) -> AVCaptureDevice {
let devices = AVCaptureDevice.devicesWithMediaType(mediaType) as![AVCaptureDevice!]
var captureDevice = devices.first

for device in devices {
if device.position == position {
captureDevice = device
break
}
}

return captureDevice!
}
}