Blame view

App/camera/ALCameraLib/ViewController/CameraViewController.swift 19.8 KB
1341bf603   Trịnh Văn Quân   version 1.1
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
  /**
  @IBAction func openCamera(_ sender: AnyObject) {
      let cameraViewController = CameraViewController(croppingEnabled: croppingEnabled, allowsLibraryAccess: libraryEnabled) { [weak self] image, asset in
          self?.imageView.image = image
          self?.dismiss(animated: true, completion: nil)
      }
  
      present(cameraViewController, animated: true, completion: nil)
  }
  
  @IBAction func openLibrary(_ sender: AnyObject) {
      let libraryViewController = CameraViewController.imagePickerViewController(croppingEnabled: croppingEnabled) { image, asset in
          let tmp: PHAsset? = asset
          self.imageView.image = image
          self.dismiss(animated: true, completion: nil)
      }
  
      present(libraryViewController, animated: true, completion: nil)
  }
  */
  
  import UIKit
  import AVFoundation
  import Photos
  
  public typealias CameraViewCompletion = (UIImage?, PHAsset?) -> Void
  
  public extension CameraViewController {
      public class func imagePickerViewController(croppingEnabled: Bool, userData: Any? = nil, completion: @escaping CameraViewCompletion) -> UINavigationController {
          let imagePicker = PhotoLibraryViewController()
          let navigationController = UINavigationController(rootViewController: imagePicker)
  
          navigationController.navigationBar.barTintColor = UIColor.black
          navigationController.navigationBar.barStyle = UIBarStyle.black
          navigationController.modalTransitionStyle = UIModalTransitionStyle.crossDissolve
  
          imagePicker.onSelectionComplete = { [weak imagePicker] asset in
              if let asset = asset {
  //                let confirmController = ConfirmViewController(asset: asset, allowsCropping: croppingEnabled)
                  let confirmController = MyConfirmViewController(asset: asset)
                  confirmController.userData = userData
                  confirmController.onComplete = { [weak imagePicker] image, asset in
                      if let image = image, let asset = asset {
                          completion(image, asset)
                      } else {
                          imagePicker?.dismiss(animated: true, completion: nil)
                      }
                  }
                  confirmController.modalTransitionStyle = UIModalTransitionStyle.crossDissolve
                  imagePicker?.present(confirmController, animated: true, completion: nil)
              } else {
                  completion(nil, nil)
              }
          }
  
          return navigationController
      }
  }
  
  public class CameraViewController: UIViewController {
      public var userData: Any?
      var didUpdateViews = false
      var allowCropping = false
      var animationRunning = false
  
      var lastInterfaceOrientation: UIInterfaceOrientation?
      var onCompletion: CameraViewCompletion?
      var volumeControl: VolumeControl?
  
      var animationDuration: TimeInterval = 0.5
      var animationSpring: CGFloat = 0.5
      var rotateAnimation: UIViewAnimationOptions = .curveLinear
  
      var cameraButtonEdgeConstraint: NSLayoutConstraint?
      var cameraButtonGravityConstraint: NSLayoutConstraint?
  
      var closeButtonEdgeConstraint: NSLayoutConstraint?
      var closeButtonGravityConstraint: NSLayoutConstraint?
  
      var containerButtonsEdgeOneConstraint: NSLayoutConstraint?
      var containerButtonsEdgeTwoConstraint: NSLayoutConstraint?
      var containerButtonsGravityConstraint: NSLayoutConstraint?
  
      var swapButtonEdgeOneConstraint: NSLayoutConstraint?
      var swapButtonEdgeTwoConstraint: NSLayoutConstraint?
      var swapButtonGravityConstraint: NSLayoutConstraint?
  
      var libraryButtonEdgeOneConstraint: NSLayoutConstraint?
      var libraryButtonEdgeTwoConstraint: NSLayoutConstraint?
      var libraryButtonGravityConstraint: NSLayoutConstraint?
  
      var flashButtonEdgeConstraint: NSLayoutConstraint?
      var flashButtonGravityConstraint: NSLayoutConstraint?
  
      var cameraOverlayEdgeOneConstraint: NSLayoutConstraint?
      var cameraOverlayEdgeTwoConstraint: NSLayoutConstraint?
      var cameraOverlayWidthConstraint: NSLayoutConstraint?
      var cameraOverlayCenterConstraint: NSLayoutConstraint?
  
      let cameraView: CameraView = {
          let cameraView = CameraView()
          cameraView.translatesAutoresizingMaskIntoConstraints = false
          return cameraView
      }()
  
      let cameraOverlay: CropOverlay = {
          let cameraOverlay = CropOverlay()
          cameraOverlay.translatesAutoresizingMaskIntoConstraints = false
          return cameraOverlay
      }()
  
      let cameraButton: UIButton = {
          let button = UIButton(frame: CGRect(x: 0, y: 0, width: 64, height: 64))
          button.translatesAutoresizingMaskIntoConstraints = false
          button.isEnabled = false
          button.setImage(UIImage(named: "cameraButton",
                  in: CameraGlobals.shared.bundle,
                  compatibleWith: nil),
                  for: .normal)
          button.setImage(UIImage(named: "cameraButtonHighlighted",
                  in: CameraGlobals.shared.bundle,
                  compatibleWith: nil),
                  for: .highlighted)
          return button
      }()
  
      let closeButton: UIButton = {
          let button = UIButton()
          button.translatesAutoresizingMaskIntoConstraints = false
          button.setImage(UIImage(named: "closeButton",
                  in: CameraGlobals.shared.bundle,
                  compatibleWith: nil),
                  for: .normal)
          return button
      }()
  
      let swapButton: UIButton = {
          let button = UIButton()
          button.translatesAutoresizingMaskIntoConstraints = false
          button.setImage(UIImage(named: "swapButton",
                  in: CameraGlobals.shared.bundle,
                  compatibleWith: nil),
                  for: .normal)
          return button
      }()
  
      let libraryButton: UIButton = {
          let button = UIButton()
          button.translatesAutoresizingMaskIntoConstraints = false
          button.setImage(UIImage(named: "libraryButton",
                  in: CameraGlobals.shared.bundle,
                  compatibleWith: nil),
                  for: .normal)
          return button
      }()
  
      let flashButton: UIButton = {
          let button = UIButton(frame: CGRect(x: 0, y: 0, width: 44, height: 44))
          button.translatesAutoresizingMaskIntoConstraints = false
          button.setImage(UIImage(named: "flashAutoIcon",
                  in: CameraGlobals.shared.bundle,
                  compatibleWith: nil),
                  for: .normal)
          return button
      }()
  
      let containerSwapLibraryButton: UIView = {
          let view = UIView()
          view.translatesAutoresizingMaskIntoConstraints = false
          return view
      }()
  
      public init(croppingEnabled: Bool, allowsLibraryAccess: Bool = true, userData: Any? = nil, completion: @escaping CameraViewCompletion) {
          super.init(nibName: nil, bundle: nil)
          self.userData = userData
          onCompletion = completion
          allowCropping = croppingEnabled
          cameraOverlay.isHidden = !allowCropping
          libraryButton.isEnabled = allowsLibraryAccess
          libraryButton.isHidden = !allowsLibraryAccess
      }
  
      required public init?(coder aDecoder: NSCoder) {
          fatalError("init(coder:) has not been implemented")
      }
  
      deinit {
          NotificationCenter.default.removeObserver(self)
      }
  
      public override var prefersStatusBarHidden: Bool {
          return true
      }
  
      public override var preferredStatusBarUpdateAnimation: UIStatusBarAnimation {
          return UIStatusBarAnimation.slide
      }
  
      /**
       * Configure the background of the superview to black
       * and add the views on this superview. Then, request
       * the update of constraints for this superview.
       */
      public override func loadView() {
          super.loadView()
          view.backgroundColor = UIColor.black
          [cameraView,
           cameraOverlay,
           cameraButton,
           closeButton,
           flashButton,
           containerSwapLibraryButton].forEach({ self.view.addSubview($0) })
          [swapButton, libraryButton].forEach({ containerSwapLibraryButton.addSubview($0) })
          view.setNeedsUpdateConstraints()
      }
  
      /**
       * Setup the constraints when the app is starting or rotating
       * the screen.
       * To avoid the override/conflict of stable constraint, these
       * stable constraint are one time configurable.
       * Any other dynamic constraint are configurable when the
       * device is rotating, based on the device orientation.
       */
      override public func updateViewConstraints() {
  
          if !didUpdateViews {
              configCameraViewConstraints()
              didUpdateViews = true
          }
  
          let statusBarOrientation = UIApplication.shared.statusBarOrientation
          let portrait = statusBarOrientation.isPortrait
  
          configCameraButtonEdgeConstraint(statusBarOrientation)
          configCameraButtonGravityConstraint(portrait)
  
          removeCloseButtonConstraints()
          configCloseButtonEdgeConstraint(statusBarOrientation)
          configCloseButtonGravityConstraint(statusBarOrientation)
  
          removeContainerConstraints()
          configContainerEdgeConstraint(statusBarOrientation)
          configContainerGravityConstraint(statusBarOrientation)
  
          removeSwapButtonConstraints()
          configSwapButtonEdgeConstraint(statusBarOrientation)
          configSwapButtonGravityConstraint(portrait)
  
          removeLibraryButtonConstraints()
          configLibraryEdgeButtonConstraint(statusBarOrientation)
          configLibraryGravityButtonConstraint(portrait)
  
          configFlashEdgeButtonConstraint(statusBarOrientation)
          configFlashGravityButtonConstraint(statusBarOrientation)
  
          let padding: CGFloat = portrait ? 16.0 : -16.0
          removeCameraOverlayEdgesConstraints()
          configCameraOverlayEdgeOneContraint(portrait, padding: padding)
          configCameraOverlayEdgeTwoConstraint(portrait, padding: padding)
          configCameraOverlayWidthConstraint(portrait)
          configCameraOverlayCenterConstraint(portrait)
  
          rotate(actualInterfaceOrientation: statusBarOrientation)
  
          super.updateViewConstraints()
      }
  
      /**
       * Add observer to check when the camera has started,
       * enable the volume buttons to take the picture,
       * configure the actions of the buttons on the screen,
       * check the permissions of access of the camera and
       * the photo library.
       * Configure the camera focus when the application
       * start, to avoid any bluried image.
       */
      public override func viewDidLoad() {
          super.viewDidLoad()
          addCameraObserver()
          addRotateObserver()
          setupVolumeControl()
          setupActions()
          checkPermissions()
          cameraView.configureFocus()
      }
  
      /**
       * Start the session of the camera.
       */
      public override func viewWillAppear(_ animated: Bool) {
          super.viewWillAppear(animated)
          cameraView.startSession()
      }
  
      /**
       * Enable the button to take the picture when the
       * camera is ready.
       */
      public override func viewDidAppear(_ animated: Bool) {
          super.viewDidAppear(animated)
          if cameraView.session?.isRunning == true {
              notifyCameraReady()
          }
      }
  
      /**
       * This method will disable the rotation of the
       */
      override public func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
          super.viewWillTransition(to: size, with: coordinator)
          lastInterfaceOrientation = UIApplication.shared.statusBarOrientation
          if animationRunning {
              return
          }
          CATransaction.begin()
          CATransaction.setDisableActions(true)
          coordinator.animate(alongsideTransition: { animation in
              self.view.setNeedsUpdateConstraints()
          }, completion: { _ in
              CATransaction.commit()
          })
      }
  
      /**
       * Observer the camera status, when it is ready,
       * it calls the method cameraReady to enable the
       * button to take the picture.
       */
      private func addCameraObserver() {
          NotificationCenter.default.addObserver(
                  self,
                  selector: #selector(notifyCameraReady),
                  name: NSNotification.Name.AVCaptureSessionDidStartRunning,
                  object: nil)
      }
  
      /**
       * Observer the device orientation to update the
       * orientation of CameraView.
       */
      private func addRotateObserver() {
          NotificationCenter.default.addObserver(
                  self,
                  selector: #selector(rotateCameraView),
                  name: NSNotification.Name.UIDeviceOrientationDidChange,
                  object: nil)
      }
  
      internal func notifyCameraReady() {
          cameraButton.isEnabled = true
      }
  
      /**
       * Attach the take of picture for any volume button.
       */
      private func setupVolumeControl() {
          volumeControl = VolumeControl(view: view) { [weak self] _ in
              if self?.cameraButton.isEnabled == true {
                  self?.capturePhoto()
              }
          }
      }
  
      /**
       * Configure the action for every button on this
       * layout.
       */
      private func setupActions() {
          cameraButton.action = { [weak self] in self?.capturePhoto() }
          swapButton.action = { [weak self] in self?.swapCamera() }
          libraryButton.action = { [weak self] in self?.showLibrary() }
          closeButton.action = { [weak self] in self?.close() }
          flashButton.action = { [weak self] in self?.toggleFlash() }
      }
  
      /**
       * Toggle the buttons status, based on the actual
       * state of the camera.
       */
      private func toggleButtons(enabled: Bool) {
          [cameraButton,
           closeButton,
           swapButton,
           libraryButton].forEach({ $0.isEnabled = enabled })
      }
  
      func rotateCameraView() {
          cameraView.rotatePreview()
      }
  
      /**
       * This method will rotate the buttons based on
       * the last and actual orientation of the device.
       */
      internal func rotate(actualInterfaceOrientation: UIInterfaceOrientation) {
  
          if lastInterfaceOrientation != nil {
              let lastTransform = CGAffineTransform(rotationAngle: CGFloat(radians(currentRotation(
                      lastInterfaceOrientation!, newOrientation: actualInterfaceOrientation))))
              self.setTransform(transform: lastTransform)
          }
  
          let transform = CGAffineTransform(rotationAngle: 0)
          animationRunning = true
  
          /**
           * Dispach delay to avoid any conflict between the CATransaction of rotation of the screen
           * and CATransaction of animation of buttons.
           */
  
          let time: DispatchTime = DispatchTime.now() + Double(1 * UInt64(NSEC_PER_SEC) / 10)
          DispatchQueue.main.asyncAfter(deadline: time) {
  
              CATransaction.begin()
              CATransaction.setDisableActions(false)
              CATransaction.commit()
  
              UIView.animate(
                      withDuration: self.animationDuration,
                      delay: 0.1,
                      usingSpringWithDamping: self.animationSpring,
                      initialSpringVelocity: 0,
                      options: self.rotateAnimation,
                      animations: {
                          self.setTransform(transform: transform)
                      }, completion: { _ in
                  self.animationRunning = false
              })
  
          }
      }
  
      func setTransform(transform: CGAffineTransform) {
          self.closeButton.transform = transform
          self.swapButton.transform = transform
          self.libraryButton.transform = transform
          self.flashButton.transform = transform
      }
  
      /**
       * Validate the permissions of the camera and
       * library, if the user do not accept these
       * permissions, it shows an view that notifies
       * the user that it not allow the permissions.
       */
      private func checkPermissions() {
          if AVCaptureDevice.authorizationStatus(forMediaType: AVMediaTypeVideo) != .authorized {
              AVCaptureDevice.requestAccess(forMediaType: AVMediaTypeVideo) { granted in
                  DispatchQueue.main.async() {
                      if !granted {
                          self.showNoPermissionsView()
                      }
                  }
              }
          }
      }
  
      /**
       * Generate the view of no permission.
       */
      private func showNoPermissionsView(library: Bool = false) {
          let permissionsView = PermissionsView(frame: view.bounds)
          let title: String
          let desc: String
  
          if library {
              title = localizedString("permissions.library.title")
              desc = localizedString("permissions.library.description")
          } else {
              title = localizedString("permissions.title")
              desc = localizedString("permissions.description")
          }
  
          permissionsView.configureInView(view, title: title, descriptiom: desc, completion: close)
      }
  
      /**
       * This method will be called when the user
       * try to take the picture.
       * It will lock any button while the shot is
       * taken, then, realease the buttons and save
       * the picture on the device.
       */
      internal func capturePhoto() {
          guard let output = cameraView.imageOutput,
                let connection = output.connection(withMediaType: AVMediaTypeVideo) else {
              return
          }
  
          if connection.isEnabled {
              toggleButtons(enabled: false)
              cameraView.capturePhoto { image in
                  guard let image = image else {
                      self.toggleButtons(enabled: true)
                      return
                  }
                  self.saveImage(image: image)
              }
          }
      }
  
      internal func saveImage(image: UIImage) {
          _ = SingleImageSaver()
                  .setImage(image)
                  .onSuccess { asset in
                      self.layoutCameraResult(asset: asset)
                  }
                  .onFailure { error in
                      self.toggleButtons(enabled: true)
                      self.showNoPermissionsView(library: true)
                  }
                  .save()
      }
  
      internal func close() {
          onCompletion?(nil, nil)
      }
  
      internal func showLibrary() {
          let imagePicker = CameraViewController.imagePickerViewController(croppingEnabled: allowCropping, userData: self.userData) { image, asset in
  
              defer {
                  self.dismiss(animated: true, completion: nil)
              }
  
              guard let image = image, let asset = asset else {
                  return
              }
  
              self.onCompletion?(image, asset)
          }
  
          present(imagePicker, animated: true) {
              self.cameraView.stopSession()
          }
      }
  
      internal func toggleFlash() {
          cameraView.cycleFlash()
  
          guard let device = cameraView.device else {
              return
          }
  
          let image = UIImage(named: flashImage(device.flashMode),
                  in: Bundle(for: CameraViewController.self),
                  compatibleWith: nil)
  
          flashButton.setImage(image, for: .normal)
      }
  
      internal func swapCamera() {
          cameraView.swapCameraInput()
          flashButton.isHidden = cameraView.currentPosition == AVCaptureDevicePosition.front
      }
  
      internal func layoutCameraResult(asset: PHAsset) {
          cameraView.stopSession()
          startConfirmController(asset: asset)
          toggleButtons(enabled: true)
      }
  
      private func startConfirmController(asset: PHAsset) {
  //        let confirmViewController = ConfirmViewController(asset: asset, allowsCropping: allowCropping)
          let confirmViewController = MyConfirmViewController(asset: asset)
          confirmViewController.userData = userData
          confirmViewController.onComplete = { image, asset in
              if let image = image, let asset = asset {
                  self.onCompletion?(image, asset)
              } else {
                  self.dismiss(animated: true, completion: nil)
              }
          }
          confirmViewController.modalTransitionStyle = UIModalTransitionStyle.crossDissolve
          present(confirmViewController, animated: true, completion: nil)
      }
  
      override open var supportedInterfaceOrientations: UIInterfaceOrientationMask {
289090880   Trịnh Văn Quân   version 1.2.2
580
          return UIInterfaceOrientationMask.portrait
1341bf603   Trịnh Văn Quân   version 1.1
581
582
      }
  }