-
Notifications
You must be signed in to change notification settings - Fork 326
Expand file tree
/
Copy pathCameraManager.swift
More file actions
2172 lines (1827 loc) · 84.7 KB
/
CameraManager.swift
File metadata and controls
2172 lines (1827 loc) · 84.7 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
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// CameraManager.swift
// camera
//
// Created by Natalia Terlecka on 10/10/14.
// Copyright (c) 2014 Imaginary Cloud. All rights reserved.
//
import AVFoundation
import CoreImage
import CoreLocation
import CoreMotion
import ImageIO
import MobileCoreServices
import Photos
import PhotosUI
import UIKit
public enum CameraState {
case ready, accessDenied, noDeviceFound, notDetermined
}
public enum CameraDevice {
case front, back
}
public enum CameraFlashMode: Int {
case off, on, auto
}
public enum CameraOutputMode {
case stillImage, videoWithMic, videoOnly
}
public enum CaptureResult {
case success(content: CaptureContent)
case failure(Error)
init(_ image: UIImage) {
self = .success(content: .image(image))
}
init(_ data: Data) {
self = .success(content: .imageData(data))
}
init(_ asset: PHAsset) {
self = .success(content: .asset(asset))
}
var imageData: Data? {
if case let .success(content) = self {
return content.asData
} else {
return nil
}
}
}
public enum CaptureContent {
case imageData(Data)
case image(UIImage)
case asset(PHAsset)
}
extension CaptureContent {
public var asImage: UIImage? {
switch self {
case let .image(image): return image
case let .imageData(data): return UIImage(data: data)
case let .asset(asset):
if let data = getImageData(fromAsset: asset) {
return UIImage(data: data)
} else {
return nil
}
}
}
public var asData: Data? {
switch self {
case let .image(image): return image.jpegData(compressionQuality: 1.0)
case let .imageData(data): return data
case let .asset(asset): return getImageData(fromAsset: asset)
}
}
private func getImageData(fromAsset asset: PHAsset) -> Data? {
var imageData: Data?
let manager = PHImageManager.default()
let options = PHImageRequestOptions()
options.version = .original
options.isSynchronous = true
manager.requestImageData(for: asset, options: options) { data, _, _, _ in
imageData = data
}
return imageData
}
}
public enum CaptureError: Error {
case noImageData
case invalidImageData
case noVideoConnection
case noSampleBuffer
case assetNotSaved
}
extension CameraManager: AVCapturePhotoCaptureDelegate {
public func photoOutput(_ output: AVCapturePhotoOutput, didFinishProcessingPhoto photoSampleBuffer: CMSampleBuffer?, previewPhoto previewPhotoSampleBuffer: CMSampleBuffer?, resolvedSettings: AVCaptureResolvedPhotoSettings, bracketSettings: AVCaptureBracketedStillImageSettings?, error: Error?) {
if let error = error {
_show(NSLocalizedString("Error", comment: ""), message: error.localizedDescription)
imageCompletion?(.failure(error))
return
}
if let sampleBuffer = photoSampleBuffer, let previewBuffer = previewPhotoSampleBuffer, let dataImage = AVCapturePhotoOutput.jpegPhotoDataRepresentation(forJPEGSampleBuffer: sampleBuffer, previewPhotoSampleBuffer: previewBuffer) {
print("image: \(UIImage(data: dataImage)?.size)") // Your Image
imageCompletion?(CaptureResult(dataImage))
}
}
}
/// Class for handling iDevices custom camera usage
open class CameraManager: NSObject, AVCaptureFileOutputRecordingDelegate, UIGestureRecognizerDelegate {
// MARK: - Public properties
// Property for custom image album name.
open var imageAlbumName: String?
// Property for custom image album name.
open var videoAlbumName: String?
/// Property for capture session to customize camera settings.
open var captureSession: AVCaptureSession?
/**
Property to determine if the manager should show the error for the user. If you want to show the errors yourself set this to false. If you want to add custom error UI set showErrorBlock property.
- note: Default value is **false**
*/
open var showErrorsToUsers = false
/// Property to determine if the manager should show the camera permission popup immediatly when it's needed or you want to show it manually. Default value is true. Be carful cause using the camera requires permission, if you set this value to false and don't ask manually you won't be able to use the camera.
open var showAccessPermissionPopupAutomatically = true
/// A block creating UI to present error message to the user. This can be customised to be presented on the Window root view controller, or to pass in the viewController which will present the UIAlertController, for example.
open var showErrorBlock: (_ erTitle: String, _ erMessage: String) -> Void = { (erTitle: String, erMessage: String) -> Void in
var alertController = UIAlertController(title: erTitle, message: erMessage, preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: { (_) -> Void in }))
if let topController = UIApplication.shared.keyWindow?.rootViewController {
topController.present(alertController, animated: true, completion: nil)
}
}
open func canSetPreset(preset: AVCaptureSession.Preset) -> Bool? {
if let validCaptureSession = captureSession {
return validCaptureSession.canSetSessionPreset(preset)
}
return nil
}
/**
Property to determine if manager should write the resources to the phone library.
- note: Default value is **true**
*/
open var writeFilesToPhoneLibrary = true
/**
Property to determine if manager should follow device orientation.
- note: Default value is **true**
*/
open var shouldRespondToOrientationChanges = true {
didSet {
if shouldRespondToOrientationChanges {
_startFollowingDeviceOrientation()
} else {
_stopFollowingDeviceOrientation()
}
}
}
/**
Property to determine if manager should horizontally flip image took by front camera.
- note: Default value is **false**
*/
open var shouldFlipFrontCameraImage = false
/**
Property to determine if manager should keep view with the same bounds when the orientation changes.
- note: Default value is **false**
*/
open var shouldKeepViewAtOrientationChanges = false
/**
Property to determine if manager should enable tap to focus on camera preview.
- note: Default value is **true**
*/
open var shouldEnableTapToFocus = true {
didSet {
focusGesture.isEnabled = shouldEnableTapToFocus
}
}
/**
Property to determine if manager should enable pinch to zoom on camera preview.
- note: Default value is **true**
*/
open var shouldEnablePinchToZoom = true {
didSet {
zoomGesture.isEnabled = shouldEnablePinchToZoom
}
}
/**
Property to determine if manager should enable pan to change exposure/brightness.
- note: Default value is **true**
*/
open var shouldEnableExposure = true {
didSet {
exposureGesture.isEnabled = shouldEnableExposure
}
}
/// Property to determine if the camera is ready to use.
open var cameraIsReady: Bool {
return cameraIsSetup
}
/// Property to determine if current device has front camera.
open var hasFrontCamera: Bool = {
let frontDevices = AVCaptureDevice.videoDevices.filter { $0.position == .front }
return !frontDevices.isEmpty
}()
/// Property to determine if current device has flash.
open var hasFlash: Bool = {
let hasFlashDevices = AVCaptureDevice.videoDevices.filter { $0.hasFlash }
return !hasFlashDevices.isEmpty
}()
/**
Property to enable or disable flip animation when switch between back and front camera.
- note: Default value is **true**
*/
open var animateCameraDeviceChange: Bool = true
/**
Property to enable or disable shutter animation when taking a picture.
- note: Default value is **true**
*/
open var animateShutter: Bool = true
/**
Property to enable or disable location services. Location services in camera is used for EXIF data.
- note: Default value is **false**
*/
open var shouldUseLocationServices: Bool = false {
didSet {
if shouldUseLocationServices {
self.locationManager = CameraLocationManager()
}
}
}
/// Property to change camera device between front and back.
open var cameraDevice: CameraDevice = .back {
didSet {
if cameraIsSetup, cameraDevice != oldValue {
if animateCameraDeviceChange {
_doFlipAnimation()
}
_updateCameraDevice(cameraDevice)
_updateIlluminationMode(flashMode)
_setupMaxZoomScale()
_zoom(2)
_orientationChanged()
}
}
}
/// Property to change camera flash mode.
open var flashMode: CameraFlashMode = .off {
didSet {
if cameraIsSetup && flashMode != oldValue {
_updateIlluminationMode(flashMode)
}
}
}
/// Property to change camera output quality.
open var cameraOutputQuality: AVCaptureSession.Preset = .high {
didSet {
if cameraIsSetup && cameraOutputQuality != oldValue {
_updateCameraQualityMode(cameraOutputQuality)
}
}
}
/// Property to change camera output.
open var cameraOutputMode: CameraOutputMode = .stillImage {
didSet {
if cameraIsSetup {
if cameraOutputMode != oldValue {
_setupOutputMode(cameraOutputMode, oldCameraOutputMode: oldValue)
}
_setupMaxZoomScale()
_zoom(2)
}
}
}
/// Property to check video recording duration when in progress.
open var recordedDuration: CMTime { return movieOutput?.recordedDuration ?? CMTime.zero }
/// Property to check video recording file size when in progress.
open var recordedFileSize: Int64 { return movieOutput?.recordedFileSize ?? 0 }
/// Property to set focus mode when tap to focus is used (_focusStart).
open var focusMode: AVCaptureDevice.FocusMode = .continuousAutoFocus
/// Property to set exposure mode when tap to focus is used (_focusStart).
open var exposureMode: AVCaptureDevice.ExposureMode = .continuousAutoExposure
/// Property to set video stabilisation mode during a video record session
open var videoStabilisationMode: AVCaptureVideoStabilizationMode = .auto {
didSet {
if oldValue != videoStabilisationMode {
_setupVideoConnection()
}
}
}
// Property to get the stabilization mode currently active
open var activeVideoStabilisationMode: AVCaptureVideoStabilizationMode {
if let movieOutput = movieOutput {
for connection in movieOutput.connections {
for port in connection.inputPorts {
if port.mediaType == AVMediaType.video {
let videoConnection = connection as AVCaptureConnection
return videoConnection.activeVideoStabilizationMode
}
}
}
}
return .off
}
// MARK: - Private properties
fileprivate var locationManager: CameraLocationManager?
fileprivate weak var embeddingView: UIView?
fileprivate var videoCompletion: ((_ videoURL: URL?, _ error: NSError?) -> Void)?
fileprivate var sessionQueue: DispatchQueue = DispatchQueue(label: "CameraSessionQueue", attributes: [])
fileprivate lazy var frontCameraDevice: AVCaptureDevice? = {
AVCaptureDevice.videoDevices.filter { $0.position == .front }.first
}()
fileprivate lazy var backCameraDevice: AVCaptureDevice? = {
let devices = AVCaptureDevice.videoDevices.filter { $0.position == .back }
if #available(iOS 13.0, *) {
return devices.first { d in
d.deviceType == .builtInTripleCamera
} ?? devices.first
}
return devices.first
}()
fileprivate lazy var mic: AVCaptureDevice? = {
AVCaptureDevice.default(for: AVMediaType.audio)
}()
fileprivate var cameraOutput: AVCapturePhotoOutput?
fileprivate var movieOutput: AVCaptureMovieFileOutput?
fileprivate var previewLayer: AVCaptureVideoPreviewLayer?
fileprivate var library: PHPhotoLibrary?
fileprivate var cameraIsSetup = false
fileprivate var cameraIsObservingDeviceOrientation = false
fileprivate var zoomScale = CGFloat(1.0)
fileprivate var beginZoomScale = CGFloat(1.0)
fileprivate var maxZoomScale = CGFloat(1.0)
fileprivate func _tempFilePath() -> URL {
let tempURL = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("tempMovie\(Date().timeIntervalSince1970)").appendingPathExtension("mp4")
return tempURL
}
fileprivate var coreMotionManager: CMMotionManager!
/// Real device orientation from DeviceMotion
fileprivate var deviceOrientation: UIDeviceOrientation = .portrait
// MARK: - CameraManager
/**
Inits a capture session and adds a preview layer to the given view. Preview layer bounds will automaticaly be set to match given view. Default session is initialized with still image output.
:param: view The view you want to add the preview layer to
:param: cameraOutputMode The mode you want capturesession to run image / video / video and microphone
:param: completion Optional completion block
:returns: Current state of the camera: Ready / AccessDenied / NoDeviceFound / NotDetermined.
*/
@discardableResult open func addPreviewLayerToView(_ view: UIView) -> CameraState {
return addPreviewLayerToView(view, newCameraOutputMode: cameraOutputMode)
}
@discardableResult open func addPreviewLayerToView(_ view: UIView, newCameraOutputMode: CameraOutputMode) -> CameraState {
return addLayerPreviewToView(view, newCameraOutputMode: newCameraOutputMode, completion: nil)
}
@discardableResult open func addLayerPreviewToView(_ view: UIView, newCameraOutputMode: CameraOutputMode, completion: (() -> Void)?) -> CameraState {
if _canLoadCamera() {
if let _ = embeddingView {
if let validPreviewLayer = previewLayer {
validPreviewLayer.removeFromSuperlayer()
}
}
if cameraIsSetup {
_addPreviewLayerToView(view)
cameraOutputMode = newCameraOutputMode
if let validCompletion = completion {
validCompletion()
}
} else {
_setupCamera {
self._addPreviewLayerToView(view)
self.cameraOutputMode = newCameraOutputMode
if let validCompletion = completion {
validCompletion()
}
}
}
}
return _checkIfCameraIsAvailable()
}
/**
Zoom in to the requested scale.
*/
open func zoom(_ scale: CGFloat) {
_zoom(scale)
}
/**
Asks the user for camera permissions. Only works if the permissions are not yet determined. Note that it'll also automaticaly ask about the microphone permissions if you selected VideoWithMic output.
:param: completion Completion block with the result of permission request
*/
open func askUserForCameraPermission(_ completion: @escaping (Bool) -> Void) {
AVCaptureDevice.requestAccess(for: AVMediaType.video, completionHandler: { (allowedAccess) -> Void in
if self.cameraOutputMode == .videoWithMic {
AVCaptureDevice.requestAccess(for: AVMediaType.audio, completionHandler: { (allowedAccess) -> Void in
DispatchQueue.main.async { () -> Void in
completion(allowedAccess)
}
})
} else {
DispatchQueue.main.async { () -> Void in
completion(allowedAccess)
}
}
})
}
/**
Stops running capture session but all setup devices, inputs and outputs stay for further reuse.
*/
open func stopCaptureSession() {
captureSession?.stopRunning()
_stopFollowingDeviceOrientation()
}
/**
Resumes capture session.
*/
open func resumeCaptureSession() {
if let validCaptureSession = captureSession {
if !validCaptureSession.isRunning, cameraIsSetup {
sessionQueue.async {
validCaptureSession.startRunning()
self._startFollowingDeviceOrientation()
}
}
} else {
if _canLoadCamera() {
if cameraIsSetup {
stopAndRemoveCaptureSession()
}
_setupCamera {
if let validEmbeddingView = self.embeddingView {
self._addPreviewLayerToView(validEmbeddingView)
}
self._startFollowingDeviceOrientation()
}
}
}
}
/**
Stops running capture session and removes all setup devices, inputs and outputs.
*/
open func stopAndRemoveCaptureSession() {
stopCaptureSession()
let oldAnimationValue = animateCameraDeviceChange
animateCameraDeviceChange = false
cameraDevice = .back
cameraIsSetup = false
previewLayer = nil
captureSession = nil
frontCameraDevice = nil
backCameraDevice = nil
mic = nil
cameraOutput = nil
movieOutput = nil
animateCameraDeviceChange = oldAnimationValue
}
/**
Captures still image from currently running capture session.
:param: imageCompletion Completion block containing the captured UIImage
*/
@available(*, deprecated)
open func capturePictureWithCompletion(_ imageCompletion: @escaping (UIImage?, NSError?) -> Void) {
func completion(_ result: CaptureResult) {
switch result {
case let .success(content):
imageCompletion(content.asImage, nil)
case .failure:
imageCompletion(nil, NSError())
}
}
capturePictureWithCompletion(completion)
}
/**
Captures still image from currently running capture session.
:param: imageCompletion Completion block containing the captured UIImage
*/
open func capturePictureWithCompletion(_ imageCompletion: @escaping (CaptureResult) -> Void) {
capturePictureDataWithCompletion { result in
guard let imageData = result.imageData else {
if case let .failure(error) = result {
imageCompletion(.failure(error))
} else {
imageCompletion(.failure(CaptureError.noImageData))
}
return
}
if self.animateShutter {
self._performShutterAnimation {
self._capturePicture(imageData, imageCompletion)
}
} else {
self._capturePicture(imageData, imageCompletion)
}
}
}
fileprivate func _capturePicture(_ imageData: Data, _ imageCompletion: @escaping (CaptureResult) -> Void) {
guard let img = UIImage(data: imageData) else {
imageCompletion(.failure(NSError()))
return
}
let image = fixOrientation(withImage: img)
let newImageData = _imageDataWithEXIF(forImage: image, imageData)! as Data
if writeFilesToPhoneLibrary {
let filePath = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("tempImg\(Int(Date().timeIntervalSince1970)).jpg")
do {
try newImageData.write(to: filePath)
// make sure that doesn't fail the first time
if PHPhotoLibrary.authorizationStatus() != .authorized {
PHPhotoLibrary.requestAuthorization { status in
if status == PHAuthorizationStatus.authorized {
self._saveImageToLibrary(atFileURL: filePath, imageCompletion)
}
}
} else {
_saveImageToLibrary(atFileURL: filePath, imageCompletion)
}
} catch {
imageCompletion(.failure(error))
return
}
}
imageCompletion(CaptureResult(newImageData))
}
fileprivate func _setVideoWithGPS(forLocation location: CLLocation) {
let metadata = AVMutableMetadataItem()
metadata.keySpace = AVMetadataKeySpace.quickTimeMetadata
metadata.key = AVMetadataKey.quickTimeMetadataKeyLocationISO6709 as NSString
metadata.identifier = AVMetadataIdentifier.quickTimeMetadataLocationISO6709
metadata.value = String(format: "%+09.5f%+010.5f%+.0fCRSWGS_84", location.coordinate.latitude, location.coordinate.longitude, location.altitude) as NSString
_getMovieOutput().metadata = [metadata]
}
fileprivate func _imageDataWithEXIF(forImage _: UIImage, _ data: Data) -> NSData? {
let cfdata: CFData = data as CFData
let source = CGImageSourceCreateWithData(cfdata, nil)!
let UTI: CFString = CGImageSourceGetType(source)!
let mutableData: CFMutableData = NSMutableData(data: data) as CFMutableData
let destination = CGImageDestinationCreateWithData(mutableData, UTI, 1, nil)!
let imageSourceRef = CGImageSourceCreateWithData(cfdata, nil)
let imageProperties = CGImageSourceCopyMetadataAtIndex(imageSourceRef!, 0, nil)!
var mutableMetadata = CGImageMetadataCreateMutableCopy(imageProperties)!
if let location = locationManager?.latestLocation {
mutableMetadata = _gpsMetadata(mutableMetadata, withLocation: location)
}
let finalMetadata: CGImageMetadata = mutableMetadata
CGImageDestinationAddImageAndMetadata(destination, UIImage(data: data)!.cgImage!, finalMetadata, nil)
CGImageDestinationFinalize(destination)
return mutableData
}
fileprivate func _gpsMetadata(_ imageMetadata: CGMutableImageMetadata, withLocation location: CLLocation) -> CGMutableImageMetadata {
let altitudeRef = Int(location.altitude < 0.0 ? 1 : 0)
let latitudeRef = location.coordinate.latitude < 0.0 ? "S" : "N"
let longitudeRef = location.coordinate.longitude < 0.0 ? "W" : "E"
let f = DateFormatter()
f.timeZone = TimeZone(abbreviation: "UTC")
f.dateFormat = "yyyy:MM:dd"
let isoDate = f.string(from: location.timestamp)
f.dateFormat = "HH:mm:ss.SSSSSS"
let isoTime = f.string(from: location.timestamp)
CGImageMetadataSetValueMatchingImageProperty(imageMetadata, kCGImagePropertyGPSDictionary, kCGImagePropertyGPSLatitudeRef, latitudeRef as CFTypeRef)
CGImageMetadataSetValueMatchingImageProperty(imageMetadata, kCGImagePropertyGPSDictionary, kCGImagePropertyGPSLatitude, abs(location.coordinate.latitude) as CFTypeRef)
CGImageMetadataSetValueMatchingImageProperty(imageMetadata, kCGImagePropertyGPSDictionary, kCGImagePropertyGPSLongitudeRef, longitudeRef as CFTypeRef)
CGImageMetadataSetValueMatchingImageProperty(imageMetadata, kCGImagePropertyGPSDictionary, kCGImagePropertyGPSLongitude, abs(location.coordinate.longitude) as CFTypeRef)
CGImageMetadataSetValueMatchingImageProperty(imageMetadata, kCGImagePropertyGPSDictionary, kCGImagePropertyGPSAltitude, Int(abs(location.altitude)) as CFTypeRef)
CGImageMetadataSetValueMatchingImageProperty(imageMetadata, kCGImagePropertyGPSDictionary, kCGImagePropertyGPSAltitudeRef, altitudeRef as CFTypeRef)
CGImageMetadataSetValueMatchingImageProperty(imageMetadata, kCGImagePropertyGPSDictionary, kCGImagePropertyGPSTimeStamp, isoTime as CFTypeRef)
CGImageMetadataSetValueMatchingImageProperty(imageMetadata, kCGImagePropertyGPSDictionary, kCGImagePropertyGPSDateStamp, isoDate as CFTypeRef)
return imageMetadata
}
fileprivate func _saveImageToLibrary(atFileURL filePath: URL, _ imageCompletion: @escaping (CaptureResult) -> Void) {
let location = locationManager?.latestLocation
let date = Date()
library?.save(imageAtURL: filePath, albumName: imageAlbumName, date: date, location: location) { asset in
guard let _ = asset else {
return imageCompletion(.failure(CaptureError.assetNotSaved))
}
}
}
/**
Captures still image from currently running capture session.
:param: imageCompletion Completion block containing the captured imageData
*/
@available(*, deprecated)
open func capturePictureDataWithCompletion(_ imageCompletion: @escaping (Data?, NSError?) -> Void) {
func completion(_ result: CaptureResult) {
switch result {
case let .success(content):
imageCompletion(content.asData, nil)
case .failure:
imageCompletion(nil, NSError())
}
}
capturePictureDataWithCompletion(completion)
}
/**
Captures still image from currently running capture session.
:param: imageCompletion Completion block containing the captured imageData
*/
internal var imageCompletion: ((CaptureResult) -> Void)?
open func capturePictureDataWithCompletion(_ imageCompletion: @escaping (CaptureResult) -> Void) {
self.imageCompletion = imageCompletion
guard cameraIsSetup else {
_show(NSLocalizedString("No capture session setup", comment: ""), message: NSLocalizedString("I can't take any picture", comment: ""))
return
}
guard cameraOutputMode == .stillImage else {
_show(NSLocalizedString("Capture session output mode video", comment: ""), message: NSLocalizedString("I can't take any picture", comment: ""))
return
}
_updateIlluminationMode(flashMode)
sessionQueue.async {
let cameraOutput = self._getStillImageOutput()
if let connection = cameraOutput.connection(with: AVMediaType.video),
connection.isEnabled {
if self.cameraDevice == CameraDevice.front, connection.isVideoMirroringSupported,
self.shouldFlipFrontCameraImage {
connection.isVideoMirrored = true
}
if connection.isVideoOrientationSupported {
connection.videoOrientation = self._currentCaptureVideoOrientation()
}
// add stuff to this
let settings = AVCapturePhotoSettings()
let previewPixelType = settings.availablePreviewPhotoPixelFormatTypes.first!
let previewFormat = [kCVPixelBufferPixelFormatTypeKey as String: previewPixelType,
kCVPixelBufferWidthKey as String: 160,
kCVPixelBufferHeightKey as String: 160]
settings.previewPhotoFormat = previewFormat
cameraOutput.capturePhoto(with: settings, delegate: self)
} else {
imageCompletion(.failure(CaptureError.noVideoConnection))
}
}
}
fileprivate func _imageOrientation(forDeviceOrientation deviceOrientation: UIDeviceOrientation, isMirrored: Bool) -> UIImage.Orientation {
switch deviceOrientation {
case .landscapeLeft:
return isMirrored ? .upMirrored : .up
case .landscapeRight:
return isMirrored ? .downMirrored : .down
default:
break
}
return isMirrored ? .leftMirrored : .right
}
/**
Starts recording a video with or without voice as in the session preset.
*/
open func startRecordingVideo() {
guard cameraOutputMode != .stillImage else {
_show(NSLocalizedString("Capture session output still image", comment: ""), message: NSLocalizedString("I can only take pictures", comment: ""))
return
}
let videoOutput = _getMovieOutput()
if shouldUseLocationServices {
let specs = [kCMMetadataFormatDescriptionMetadataSpecificationKey_Identifier as String: AVMetadataIdentifier.quickTimeMetadataLocationISO6709,
kCMMetadataFormatDescriptionMetadataSpecificationKey_DataType as String: kCMMetadataDataType_QuickTimeMetadataLocation_ISO6709 as String] as [String: Any]
var locationMetadataDesc: CMFormatDescription?
CMMetadataFormatDescriptionCreateWithMetadataSpecifications(allocator: kCFAllocatorDefault, metadataType: kCMMetadataFormatType_Boxed, metadataSpecifications: [specs] as CFArray, formatDescriptionOut: &locationMetadataDesc)
// Create the metadata input and add it to the session.
guard let captureSession = captureSession, let locationMetadata = locationMetadataDesc else {
return
}
let newLocationMetadataInput = AVCaptureMetadataInput(formatDescription: locationMetadata, clock: CMClockGetHostTimeClock())
captureSession.addInputWithNoConnections(newLocationMetadataInput)
// Connect the location metadata input to the movie file output.
let inputPort = newLocationMetadataInput.ports[0]
captureSession.addConnection(AVCaptureConnection(inputPorts: [inputPort], output: videoOutput))
}
_updateIlluminationMode(flashMode)
videoOutput.startRecording(to: _tempFilePath(), recordingDelegate: self)
}
/**
Stop recording a video. Save it to the cameraRoll and give back the url.
*/
open func stopVideoRecording(_ completion: ((_ videoURL: URL?, _ error: NSError?) -> Void)?) {
if let runningMovieOutput = movieOutput,
runningMovieOutput.isRecording {
videoCompletion = completion
runningMovieOutput.stopRecording()
}
}
/**
The signature for a handler.
The success value is the string representation of a scanned QR code, if any.
*/
public typealias QRCodeDetectionHandler = (Result<String, Error>) -> Void
/**
Start detecting QR codes.
*/
open func startQRCodeDetection(_ handler: @escaping QRCodeDetectionHandler) {
guard let captureSession = self.captureSession
else { return }
let output = AVCaptureMetadataOutput()
guard captureSession.canAddOutput(output)
else { return }
qrCodeDetectionHandler = handler
captureSession.addOutput(output)
// Note: The object types must be set after the output was added to the capture session.
output.setMetadataObjectsDelegate(self, queue: DispatchQueue.main)
output.metadataObjectTypes = [.qr, .ean8, .ean13, .pdf417].filter { output.availableMetadataObjectTypes.contains($0) }
}
/**
Stop detecting QR codes.
*/
open func stopQRCodeDetection() {
qrCodeDetectionHandler = nil
if let output = qrOutput {
captureSession?.removeOutput(output)
}
qrOutput = nil
}
/**
The stored handler for QR codes.
*/
private var qrCodeDetectionHandler: QRCodeDetectionHandler?
/**
The stored meta data output; used to detect QR codes.
*/
private var qrOutput: AVCaptureOutput?
/**
Check if the device rotation is locked
*/
open func deviceOrientationMatchesInterfaceOrientation() -> Bool {
return deviceOrientation == UIDevice.current.orientation
}
/**
Current camera status.
:returns: Current state of the camera: Ready / AccessDenied / NoDeviceFound / NotDetermined
*/
open func currentCameraStatus() -> CameraState {
return _checkIfCameraIsAvailable()
}
/**
Change current flash mode to next value from available ones.
:returns: Current flash mode: Off / On / Auto
*/
open func changeFlashMode() -> CameraFlashMode {
guard let newFlashMode = CameraFlashMode(rawValue: (flashMode.rawValue + 1) % 3) else { return flashMode }
flashMode = newFlashMode
return flashMode
}
/**
Check the camera device has flash
*/
open func hasFlash(for cameraDevice: CameraDevice) -> Bool {
let devices = AVCaptureDevice.videoDevices
for device in devices {
if device.position == .back, cameraDevice == .back {
return device.hasFlash
} else if device.position == .front, cameraDevice == .front {
return device.hasFlash
}
}
return false
}
// MARK: - AVCaptureFileOutputRecordingDelegate
public func fileOutput(_: AVCaptureFileOutput, didStartRecordingTo _: URL, from _: [AVCaptureConnection]) {
captureSession?.beginConfiguration()
if flashMode != .off {
_updateIlluminationMode(flashMode)
}
captureSession?.commitConfiguration()
}
open func fileOutput(_: AVCaptureFileOutput, didFinishRecordingTo outputFileURL: URL, from _: [AVCaptureConnection], error: Error?) {
if let error = error {
_show(NSLocalizedString("Unable to save video to the device", comment: ""), message: error.localizedDescription)
} else {
if writeFilesToPhoneLibrary {
if PHPhotoLibrary.authorizationStatus() == .authorized {
_saveVideoToLibrary(outputFileURL)
} else {
PHPhotoLibrary.requestAuthorization { autorizationStatus in
if autorizationStatus == .authorized {
self._saveVideoToLibrary(outputFileURL)
}
}
}
} else {
_executeVideoCompletionWithURL(outputFileURL, error: error as NSError?)
}
}
}
fileprivate func _saveVideoToLibrary(_ fileURL: URL) {
let location = locationManager?.latestLocation
let date = Date()
library?.save(videoAtURL: fileURL, albumName: videoAlbumName, date: date, location: location, completion: { _ in
self._executeVideoCompletionWithURL(fileURL, error: nil)
})
}
// MARK: - UIGestureRecognizerDelegate
fileprivate lazy var zoomGesture = UIPinchGestureRecognizer()
fileprivate func attachZoom(_ view: UIView) {
DispatchQueue.main.async {
self.zoomGesture.addTarget(self, action: #selector(CameraManager._zoomStart(_:)))
view.addGestureRecognizer(self.zoomGesture)
self.zoomGesture.delegate = self
}
}
open func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
if gestureRecognizer.isKind(of: UIPinchGestureRecognizer.self) {
beginZoomScale = zoomScale
}
return true
}
@objc fileprivate func _zoomStart(_ recognizer: UIPinchGestureRecognizer) {
guard let view = embeddingView,
let previewLayer = previewLayer
else { return }
var allTouchesOnPreviewLayer = true
let numTouch = recognizer.numberOfTouches
for i in 0 ..< numTouch {
let location = recognizer.location(ofTouch: i, in: view)
let convertedTouch = previewLayer.convert(location, from: previewLayer.superlayer)
if !previewLayer.contains(convertedTouch) {
allTouchesOnPreviewLayer = false
break
}
}
if allTouchesOnPreviewLayer {
_zoom(recognizer.scale)
}
}
fileprivate func _zoom(_ scale: CGFloat) {
let device: AVCaptureDevice?
switch cameraDevice {
case .back:
device = backCameraDevice
case .front:
device = frontCameraDevice
}
do {
let captureDevice = device
try captureDevice?.lockForConfiguration()
zoomScale = max(1.0, min(beginZoomScale * scale, maxZoomScale))
captureDevice?.videoZoomFactor = zoomScale
captureDevice?.unlockForConfiguration()