/
CameraPlugin.swift
404 lines (373 loc) · 16.6 KB
/
CameraPlugin.swift
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
import Foundation
import Capacitor
import Photos
import PhotosUI
@objc(CAPCameraPlugin)
public class CameraPlugin: CAPPlugin {
private var call: CAPPluginCall?
private var settings = CameraSettings()
private let defaultSource = CameraSource.prompt
private let defaultDirection = CameraDirection.rear
private var imageCounter = 0
@objc override public func checkPermissions(_ call: CAPPluginCall) {
var result: [String: Any] = [:]
for permission in CameraPermissionType.allCases {
let state: String
switch permission {
case .camera:
state = AVCaptureDevice.authorizationStatus(for: .video).authorizationState
case .photos:
if #available(iOS 14, *) {
state = PHPhotoLibrary.authorizationStatus(for: .readWrite).authorizationState
} else {
state = PHPhotoLibrary.authorizationStatus().authorizationState
}
}
result[permission.rawValue] = state
}
call.resolve(result)
}
@objc override public func requestPermissions(_ call: CAPPluginCall) {
// get the list of desired types, if passed
let typeList = call.getArray("permissions", String.self)?.compactMap({ (type) -> CameraPermissionType? in
return CameraPermissionType(rawValue: type)
}) ?? []
// otherwise check everything
let permissions: [CameraPermissionType] = (typeList.count > 0) ? typeList : CameraPermissionType.allCases
// request the permissions
let group = DispatchGroup()
for permission in permissions {
switch permission {
case .camera:
group.enter()
AVCaptureDevice.requestAccess(for: .video) { _ in
group.leave()
}
case .photos:
group.enter()
if #available(iOS 14, *) {
PHPhotoLibrary.requestAuthorization(for: .readWrite) { (_) in
group.leave()
}
} else {
PHPhotoLibrary.requestAuthorization({ (_) in
group.leave()
})
}
}
}
group.notify(queue: DispatchQueue.main) { [weak self] in
self?.checkPermissions(call)
}
}
@objc func getPhoto(_ call: CAPPluginCall) {
self.call = call
self.settings = cameraSettings(from: call)
// Make sure they have all the necessary info.plist settings
if let missingUsageDescription = checkUsageDescriptions() {
CAPLog.print("⚡️ ", self.pluginId, "-", missingUsageDescription)
call.reject(missingUsageDescription)
bridge?.alert("Camera Error", "Missing required usage description. See console for more information")
return
}
DispatchQueue.main.async {
switch self.settings.source {
case .prompt:
self.showPrompt()
case .camera:
self.showCamera()
case .photos:
self.showPhotos()
}
}
}
private func checkUsageDescriptions() -> String? {
if let dict = Bundle.main.infoDictionary {
for key in CameraPropertyListKeys.allCases where dict[key.rawValue] == nil {
return key.missingMessage
}
}
return nil
}
private func cameraSettings(from call: CAPPluginCall) -> CameraSettings {
var settings = CameraSettings()
settings.jpegQuality = min(abs(CGFloat(call.getFloat("quality") ?? 100.0)) / 100.0, 1.0)
settings.allowEditing = call.getBool("allowEditing") ?? false
settings.source = CameraSource(rawValue: call.getString("source") ?? defaultSource.rawValue) ?? defaultSource
settings.direction = CameraDirection(rawValue: call.getString("direction") ?? defaultDirection.rawValue) ?? defaultDirection
if let typeString = call.getString("resultType"), let type = CameraResultType(rawValue: typeString) {
settings.resultType = type
}
settings.saveToGallery = call.getBool("saveToGallery") ?? false
// Get the new image dimensions if provided
settings.width = CGFloat(call.getInt("width") ?? 0)
settings.height = CGFloat(call.getInt("height") ?? 0)
if settings.width > 0 || settings.height > 0 {
// We resize only if a dimension was provided
settings.shouldResize = true
}
settings.shouldCorrectOrientation = call.getBool("correctOrientation") ?? true
settings.userPromptText = CameraPromptText(title: call.getString("promptLabelHeader"),
photoAction: call.getString("promptLabelPhoto"),
cameraAction: call.getString("promptLabelPicture"),
cancelAction: call.getString("promptLabelCancel"))
if let styleString = call.getString("presentationStyle"), styleString == "popover" {
settings.presentationStyle = .popover
} else {
settings.presentationStyle = .fullScreen
}
return settings
}
}
// public delegate methods
extension CameraPlugin: UIImagePickerControllerDelegate, UINavigationControllerDelegate, UIPopoverPresentationControllerDelegate {
public func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
picker.dismiss(animated: true)
self.call?.reject("User cancelled photos app")
}
public func popoverPresentationControllerDidDismissPopover(_ popoverPresentationController: UIPopoverPresentationController) {
self.call?.reject("User cancelled photos app")
}
public func presentationControllerDidDismiss(_ presentationController: UIPresentationController) {
self.call?.reject("User cancelled photos app")
}
public func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any]) {
picker.dismiss(animated: true, completion: nil)
if let processedImage = processImage(from: info) {
returnProcessedImage(processedImage)
} else {
self.call?.reject("Error processing image")
}
}
}
@available(iOS 14, *)
extension CameraPlugin: PHPickerViewControllerDelegate {
public func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {
picker.dismiss(animated: true, completion: nil)
guard let result = results.first else {
self.call?.reject("User cancelled photos app")
return
}
guard result.itemProvider.canLoadObject(ofClass: UIImage.self) else {
self.call?.reject("Error loading image")
return
}
// extract the image
result.itemProvider.loadObject(ofClass: UIImage.self) { [weak self] (reading, _) in
if let image = reading as? UIImage {
var asset: PHAsset?
if let assetId = result.assetIdentifier {
asset = PHAsset.fetchAssets(withLocalIdentifiers: [assetId], options: nil).firstObject
}
if let processedImage = self?.processedImage(from: image, with: asset?.imageData) {
self?.returnProcessedImage(processedImage)
return
}
}
self?.call?.reject("Error loading image")
}
}
}
private extension CameraPlugin {
func returnProcessedImage(_ processedImage: ProcessedImage) {
guard let jpeg = processedImage.generateJPEG(with: settings.jpegQuality) else {
self.call?.reject("Unable to convert image to jpeg")
return
}
if settings.resultType == CameraResultType.base64 {
call?.resolve([
"base64String": jpeg.base64EncodedString(),
"exif": processedImage.exifData,
"format": "jpeg"
])
} else if settings.resultType == CameraResultType.dataURL {
call?.resolve([
"dataUrl": "data:image/jpeg;base64," + jpeg.base64EncodedString(),
"exif": processedImage.exifData,
"format": "jpeg"
])
} else if settings.resultType == CameraResultType.uri {
guard let fileURL = try? saveTemporaryImage(jpeg),
let webURL = bridge?.portablePath(fromLocalURL: fileURL) else {
call?.reject("Unable to get portable path to file")
return
}
call?.resolve([
"path": fileURL.absoluteString,
"exif": processedImage.exifData,
"webPath": webURL.absoluteString,
"format": "jpeg"
])
}
}
func showPrompt() {
// Build the action sheet
let alert = UIAlertController(title: settings.userPromptText.title, message: nil, preferredStyle: UIAlertController.Style.actionSheet)
alert.addAction(UIAlertAction(title: settings.userPromptText.photoAction, style: .default, handler: { [weak self] (_: UIAlertAction) in
self?.showPhotos()
}))
alert.addAction(UIAlertAction(title: settings.userPromptText.cameraAction, style: .default, handler: { [weak self] (_: UIAlertAction) in
self?.showCamera()
}))
alert.addAction(UIAlertAction(title: settings.userPromptText.cancelAction, style: .cancel, handler: { [weak self] (_: UIAlertAction) in
self?.call?.reject("User cancelled photos app")
}))
self.setCenteredPopover(alert)
self.bridge?.viewController?.present(alert, animated: true, completion: nil)
}
func showCamera() {
// check if we have a camera
if (bridge?.isSimEnvironment ?? false) || !UIImagePickerController.isSourceTypeAvailable(UIImagePickerController.SourceType.camera) {
CAPLog.print("⚡️ ", self.pluginId, "-", "Camera not available in simulator")
bridge?.alert("Camera Error", "Camera not available in Simulator")
call?.reject("Camera not available while running in Simulator")
return
}
// check for permission
let authStatus = AVCaptureDevice.authorizationStatus(for: .video)
if authStatus == .restricted || authStatus == .denied {
call?.reject("User denied access to camera")
return
}
// we either already have permission or can prompt
AVCaptureDevice.requestAccess(for: .video) { [weak self] granted in
if granted {
DispatchQueue.main.async {
self?.presentCameraPicker()
}
} else {
self?.call?.reject("User denied access to camera")
}
}
}
func showPhotos() {
// check for permission
let authStatus = PHPhotoLibrary.authorizationStatus()
if authStatus == .restricted || authStatus == .denied {
call?.reject("User denied access to photos")
return
}
// we either already have permission or can prompt
if authStatus == .authorized {
presentSystemAppropriateImagePicker()
} else {
PHPhotoLibrary.requestAuthorization({ [weak self] (status) in
if status == PHAuthorizationStatus.authorized {
DispatchQueue.main.async { [weak self] in
self?.presentSystemAppropriateImagePicker()
}
} else {
self?.call?.reject("User denied access to photos")
}
})
}
}
func presentCameraPicker() {
let picker = UIImagePickerController()
picker.delegate = self
picker.allowsEditing = self.settings.allowEditing
// select the input
picker.sourceType = .camera
if settings.direction == .rear, UIImagePickerController.isCameraDeviceAvailable(.rear) {
picker.cameraDevice = .rear
} else if settings.direction == .front, UIImagePickerController.isCameraDeviceAvailable(.front) {
picker.cameraDevice = .front
}
// present
picker.modalPresentationStyle = settings.presentationStyle
if settings.presentationStyle == .popover {
picker.popoverPresentationController?.delegate = self
setCenteredPopover(picker)
}
bridge?.viewController?.present(picker, animated: true, completion: nil)
}
func presentSystemAppropriateImagePicker() {
if #available(iOS 14, *) {
presentPhotoPicker()
} else {
presentImagePicker()
}
}
func presentImagePicker() {
let picker = UIImagePickerController()
picker.delegate = self
picker.allowsEditing = self.settings.allowEditing
// select the input
picker.sourceType = .photoLibrary
// present
picker.modalPresentationStyle = settings.presentationStyle
if settings.presentationStyle == .popover {
picker.popoverPresentationController?.delegate = self
setCenteredPopover(picker)
}
bridge?.viewController?.present(picker, animated: true, completion: nil)
}
@available(iOS 14, *)
func presentPhotoPicker() {
var configuration = PHPickerConfiguration(photoLibrary: PHPhotoLibrary.shared())
configuration.selectionLimit = 1
configuration.filter = .images
let picker = PHPickerViewController(configuration: configuration)
picker.delegate = self
// present
picker.modalPresentationStyle = settings.presentationStyle
if settings.presentationStyle == .popover {
picker.popoverPresentationController?.delegate = self
setCenteredPopover(picker)
}
bridge?.viewController?.present(picker, animated: true, completion: nil)
}
func saveTemporaryImage(_ data: Data) throws -> URL {
var url: URL
repeat {
imageCounter += 1
url = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("photo-\(imageCounter).jpg")
} while FileManager.default.fileExists(atPath: url.path)
try data.write(to: url, options: .atomic)
return url
}
func processImage(from info: [UIImagePickerController.InfoKey: Any]) -> ProcessedImage? {
var selectedImage: UIImage?
var flags: PhotoFlags = []
// get the image
if let edited = info[UIImagePickerController.InfoKey.editedImage] as? UIImage {
selectedImage = edited // use the edited version
flags = flags.union([.edited])
} else if let original = info[UIImagePickerController.InfoKey.originalImage] as? UIImage {
selectedImage = original // use the original version
}
guard let image = selectedImage else {
return nil
}
var metadata: [String: Any] = [:]
// get the image's metadata from the picker or from the photo album
if let photoMetadata = info[UIImagePickerController.InfoKey.mediaMetadata] as? [String: Any] {
metadata = photoMetadata
} else {
flags = flags.union([.gallery])
}
if let asset = info[UIImagePickerController.InfoKey.phAsset] as? PHAsset {
metadata = asset.imageData
}
// get the result
let result = processedImage(from: image, with: metadata)
// conditionally save the image
if settings.saveToGallery && (flags.contains(.edited) == true || flags.contains(.gallery) == false) {
UIImageWriteToSavedPhotosAlbum(result.image, nil, nil, nil)
}
return result
}
func processedImage(from image: UIImage, with metadata: [String: Any]?) -> ProcessedImage {
var result = ProcessedImage(image: image, metadata: metadata ?? [:])
// resizing the image only makes sense if we have real values to which to constrain it
if settings.shouldResize, settings.width > 0 || settings.height > 0 {
result.image = result.image.reformat(to: CGSize(width: settings.width, height: settings.height))
result.overwriteMetadataOrientation(to: 1)
} else if settings.shouldCorrectOrientation {
// resizing implicitly reformats the image so this is only needed if we aren't resizing
result.image = result.image.reformat()
result.overwriteMetadataOrientation(to: 1)
}
return result
}
}