-
Notifications
You must be signed in to change notification settings - Fork 1
/
ImagePickerManager.m
738 lines (639 loc) · 33.2 KB
/
ImagePickerManager.m
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
#import "ImagePickerManager.h"
#import <React/RCTConvert.h>
#import <AssetsLibrary/AssetsLibrary.h>
#import <AVFoundation/AVFoundation.h>
#import <Photos/Photos.h>
@import MobileCoreServices;
@interface ImagePickerManager ()
@property (nonatomic, strong) UIAlertController *alertController;
@property (nonatomic, strong) UIImagePickerController *picker;
@property (nonatomic, strong) RCTResponseSenderBlock callback;
@property (nonatomic, strong) NSDictionary *defaultOptions;
@property (nonatomic, retain) NSMutableDictionary *options, *response;
@property (nonatomic, strong) NSArray *customButtons;
@end
@implementation ImagePickerManager
RCT_EXPORT_MODULE();
RCT_EXPORT_METHOD(launchCamera:(NSDictionary *)options callback:(RCTResponseSenderBlock)callback)
{
self.callback = callback;
[self launchImagePicker:RNImagePickerTargetCamera options:options];
}
RCT_EXPORT_METHOD(launchImageLibrary:(NSDictionary *)options callback:(RCTResponseSenderBlock)callback)
{
self.callback = callback;
[self launchImagePicker:RNImagePickerTargetLibrarySingleImage options:options];
}
RCT_EXPORT_METHOD(showImagePicker:(NSDictionary *)options callback:(RCTResponseSenderBlock)callback)
{
self.callback = callback; // Save the callback so we can use it from the delegate methods
self.options = options;
NSString *title = [self.options valueForKey:@"title"];
if ([title isEqual:[NSNull null]] || title.length == 0) {
title = nil; // A more visually appealing UIAlertControl is displayed with a nil title rather than title = @""
}
NSString *cancelTitle = [self.options valueForKey:@"cancelButtonTitle"];
NSString *takePhotoButtonTitle = [self.options valueForKey:@"takePhotoButtonTitle"];
NSString *chooseFromLibraryButtonTitle = [self.options valueForKey:@"chooseFromLibraryButtonTitle"];
self.alertController = [UIAlertController alertControllerWithTitle:title message:nil preferredStyle:UIAlertControllerStyleActionSheet];
UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:cancelTitle style:UIAlertActionStyleCancel handler:^(UIAlertAction * action) {
self.callback(@[@{@"didCancel": @YES}]); // Return callback for 'cancel' action (if is required)
}];
[self.alertController addAction:cancelAction];
if (![takePhotoButtonTitle isEqual:[NSNull null]] && takePhotoButtonTitle.length > 0) {
UIAlertAction *takePhotoAction = [UIAlertAction actionWithTitle:takePhotoButtonTitle style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
[self actionHandler:action];
}];
[self.alertController addAction:takePhotoAction];
}
if (![chooseFromLibraryButtonTitle isEqual:[NSNull null]] && chooseFromLibraryButtonTitle.length > 0) {
UIAlertAction *chooseFromLibraryAction = [UIAlertAction actionWithTitle:chooseFromLibraryButtonTitle style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
[self actionHandler:action];
}];
[self.alertController addAction:chooseFromLibraryAction];
}
// Add custom buttons to action sheet
if ([self.options objectForKey:@"customButtons"] && [[self.options objectForKey:@"customButtons"] isKindOfClass:[NSArray class]]) {
self.customButtons = [self.options objectForKey:@"customButtons"];
for (NSString *button in self.customButtons) {
NSString *title = [button valueForKey:@"title"];
UIAlertAction *customAction = [UIAlertAction actionWithTitle:title style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
[self actionHandler:action];
}];
[self.alertController addAction:customAction];
}
}
dispatch_async(dispatch_get_main_queue(), ^{
UIViewController *root = [[[[UIApplication sharedApplication] delegate] window] rootViewController];
while (root.presentedViewController != nil) {
root = root.presentedViewController;
}
/* On iPad, UIAlertController presents a popover view rather than an action sheet like on iPhone. We must provide the location
of the location to show the popover in this case. For simplicity, we'll just display it on the bottom center of the screen
to mimic an action sheet */
self.alertController.popoverPresentationController.sourceView = root.view;
self.alertController.popoverPresentationController.sourceRect = CGRectMake(root.view.bounds.size.width / 2.0, root.view.bounds.size.height, 1.0, 1.0);
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
self.alertController.popoverPresentationController.permittedArrowDirections = 0;
for (id subview in self.alertController.view.subviews) {
if ([subview isMemberOfClass:[UIView class]]) {
((UIView *)subview).backgroundColor = [UIColor whiteColor];
}
}
}
[root presentViewController:self.alertController animated:YES completion:nil];
});
}
- (void)actionHandler:(UIAlertAction *)action
{
// If button title is one of the keys in the customButtons dictionary return the value as a callback
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"title==%@", action.title];
NSArray *results = [self.customButtons filteredArrayUsingPredicate:predicate];
if (results.count > 0) {
NSString *customButtonStr = [[results objectAtIndex:0] objectForKey:@"name"];
if (customButtonStr) {
self.callback(@[@{@"customButton": customButtonStr}]);
return;
}
}
if ([action.title isEqualToString:[self.options valueForKey:@"takePhotoButtonTitle"]]) { // Take photo
[self launchImagePicker:RNImagePickerTargetCamera];
}
else if ([action.title isEqualToString:[self.options valueForKey:@"chooseFromLibraryButtonTitle"]]) { // Choose from library
[self launchImagePicker:RNImagePickerTargetLibrarySingleImage];
}
}
- (void)launchImagePicker:(RNImagePickerTarget)target options:(NSDictionary *)options
{
self.options = options;
[self launchImagePicker:target];
}
- (void)launchImagePicker:(RNImagePickerTarget)target
{
self.picker = [[UIImagePickerController alloc] init];
if (target == RNImagePickerTargetCamera) {
#if TARGET_IPHONE_SIMULATOR
self.callback(@[@{@"error": @"Camera not available on simulator"}]);
return;
#else
self.picker.sourceType = UIImagePickerControllerSourceTypeCamera;
if ([[self.options objectForKey:@"cameraType"] isEqualToString:@"front"]) {
self.picker.cameraDevice = UIImagePickerControllerCameraDeviceFront;
}
else { // "back"
self.picker.cameraDevice = UIImagePickerControllerCameraDeviceRear;
}
#endif
}
else { // RNImagePickerTargetLibrarySingleImage
self.picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
}
if ([[self.options objectForKey:@"mediaType"] isEqualToString:@"video"]
|| [[self.options objectForKey:@"mediaType"] isEqualToString:@"mixed"]) {
if ([[self.options objectForKey:@"videoQuality"] isEqualToString:@"high"]) {
self.picker.videoQuality = UIImagePickerControllerQualityTypeHigh;
}
else if ([[self.options objectForKey:@"videoQuality"] isEqualToString:@"low"]) {
self.picker.videoQuality = UIImagePickerControllerQualityTypeLow;
}
else {
self.picker.videoQuality = UIImagePickerControllerQualityTypeMedium;
}
id durationLimit = [self.options objectForKey:@"durationLimit"];
if (durationLimit) {
self.picker.videoMaximumDuration = [durationLimit doubleValue];
self.picker.allowsEditing = NO;
}
}
if ([[self.options objectForKey:@"mediaType"] isEqualToString:@"video"]) {
self.picker.mediaTypes = @[(NSString *)kUTTypeMovie];
} else if ([[self.options objectForKey:@"mediaType"] isEqualToString:@"mixed"]) {
self.picker.mediaTypes = @[(NSString *)kUTTypeMovie, (NSString *)kUTTypeImage];
} else {
self.picker.mediaTypes = @[(NSString *)kUTTypeImage];
}
if ([[self.options objectForKey:@"allowsEditing"] boolValue]) {
self.picker.allowsEditing = true;
}
self.picker.modalPresentationStyle = UIModalPresentationCurrentContext;
self.picker.delegate = self;
// Check permissions
void (^showPickerViewController)() = ^void() {
dispatch_async(dispatch_get_main_queue(), ^{
UIViewController *root = [[[[UIApplication sharedApplication] delegate] window] rootViewController];
while (root.presentedViewController != nil) {
root = root.presentedViewController;
}
[root presentViewController:self.picker animated:YES completion:nil];
});
};
if (target == RNImagePickerTargetCamera) {
[self checkCameraPermissions:^(BOOL granted) {
if (!granted) {
if(![self showPermissionAlert]){
self.callback(@[@{@"error": @"Camera permissions not granted"}]);
}
}else{
showPickerViewController();
}
}];
}
else { // RNImagePickerTargetLibrarySingleImage
[self checkPhotosPermissions:^(BOOL granted) {
if (!granted) {
if(![self showPermissionAlert]){
self.callback(@[@{@"error": @"Photo library permissions not granted"}]);
}
}else{
showPickerViewController();
}
}];
}
}
- (NSString * _Nullable)originalFilenameForAsset:(PHAsset * _Nullable)asset assetType:(PHAssetResourceType)type {
if (!asset) { return nil; }
PHAssetResource *originalResource;
// Get the underlying resources for the PHAsset (PhotoKit)
NSArray<PHAssetResource *> *pickedAssetResources = [PHAssetResource assetResourcesForAsset:asset];
// Find the original resource (underlying image) for the asset, which has the desired filename
for (PHAssetResource *resource in pickedAssetResources) {
if (resource.type == type) {
originalResource = resource;
}
}
return originalResource.originalFilename;
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
dispatch_block_t dismissCompletionBlock = ^{
NSURL *imageURL = [info valueForKey:UIImagePickerControllerReferenceURL];
NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
NSString *fileName;
if ([mediaType isEqualToString:(NSString *)kUTTypeImage]) {
NSString *tempFileName = [[NSUUID UUID] UUIDString];
if (imageURL && [[imageURL absoluteString] rangeOfString:@"ext=GIF"].location != NSNotFound) {
fileName = [tempFileName stringByAppendingString:@".gif"];
}
else if ([[[self.options objectForKey:@"imageFileType"] stringValue] isEqualToString:@"png"]) {
fileName = [tempFileName stringByAppendingString:@".png"];
}
else {
fileName = [tempFileName stringByAppendingString:@".jpg"];
}
}
else {
NSURL *videoURL = info[UIImagePickerControllerMediaURL];
fileName = videoURL.lastPathComponent;
}
// We default to path to the temporary directory
NSString *path = [[NSTemporaryDirectory()stringByStandardizingPath] stringByAppendingPathComponent:fileName];
// If storage options are provided, we use the documents directory which is persisted
if ([self.options objectForKey:@"storageOptions"] && [[self.options objectForKey:@"storageOptions"] isKindOfClass:[NSDictionary class]]) {
NSDictionary *storageOptions = [self.options objectForKey:@"storageOptions"];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
path = [documentsDirectory stringByAppendingPathComponent:fileName];
// Creates documents subdirectory, if provided
if ([storageOptions objectForKey:@"path"]) {
NSString *newPath = [documentsDirectory stringByAppendingPathComponent:[storageOptions objectForKey:@"path"]];
NSError *error;
[[NSFileManager defaultManager] createDirectoryAtPath:newPath withIntermediateDirectories:YES attributes:nil error:&error];
if (error) {
NSLog(@"Error creating documents subdirectory: %@", error);
self.callback(@[@{@"error": error.localizedFailureReason}]);
return;
}
else {
path = [newPath stringByAppendingPathComponent:fileName];
}
}
}
// Create the response object
self.response = [[NSMutableDictionary alloc] init];
if ([mediaType isEqualToString:(NSString *)kUTTypeImage]) { // PHOTOS
UIImage *image;
if ([[self.options objectForKey:@"allowsEditing"] boolValue]) {
image = [info objectForKey:UIImagePickerControllerEditedImage];
}
else {
image = [info objectForKey:UIImagePickerControllerOriginalImage];
}
if (imageURL) {
PHAsset *pickedAsset = [PHAsset fetchAssetsWithALAssetURLs:@[imageURL] options:nil].lastObject;
NSString *originalFilename = [self originalFilenameForAsset:pickedAsset assetType:PHAssetResourceTypePhoto];
self.response[@"fileName"] = originalFilename ?: [NSNull null];
if (pickedAsset.location) {
self.response[@"latitude"] = @(pickedAsset.location.coordinate.latitude);
self.response[@"longitude"] = @(pickedAsset.location.coordinate.longitude);
}
if (pickedAsset.creationDate) {
self.response[@"timestamp"] = [[ImagePickerManager ISO8601DateFormatter] stringFromDate:pickedAsset.creationDate];
}
}
// GIFs break when resized, so we handle them differently
if (imageURL && [[imageURL absoluteString] rangeOfString:@"ext=GIF"].location != NSNotFound) {
ALAssetsLibrary* assetsLibrary = [[ALAssetsLibrary alloc] init];
[assetsLibrary assetForURL:imageURL resultBlock:^(ALAsset *asset) {
ALAssetRepresentation *rep = [asset defaultRepresentation];
Byte *buffer = (Byte*)malloc(rep.size);
NSUInteger buffered = [rep getBytes:buffer fromOffset:0.0 length:rep.size error:nil];
NSData *data = [NSData dataWithBytesNoCopy:buffer length:buffered freeWhenDone:YES];
[data writeToFile:path atomically:YES];
NSMutableDictionary *gifResponse = [[NSMutableDictionary alloc] init];
[gifResponse setObject:@(image.size.width) forKey:@"width"];
[gifResponse setObject:@(image.size.height) forKey:@"height"];
BOOL vertical = (image.size.width < image.size.height) ? YES : NO;
[gifResponse setObject:@(vertical) forKey:@"isVertical"];
if (![[self.options objectForKey:@"noData"] boolValue]) {
NSString *dataString = [data base64EncodedStringWithOptions:0];
[gifResponse setObject:dataString forKey:@"data"];
}
NSURL *fileURL = [NSURL fileURLWithPath:path];
[gifResponse setObject:[fileURL absoluteString] forKey:@"uri"];
NSNumber *fileSizeValue = nil;
NSError *fileSizeError = nil;
[fileURL getResourceValue:&fileSizeValue forKey:NSURLFileSizeKey error:&fileSizeError];
if (fileSizeValue){
[gifResponse setObject:fileSizeValue forKey:@"fileSize"];
}
self.callback(@[gifResponse]);
} failureBlock:^(NSError *error) {
self.callback(@[@{@"error": error.localizedFailureReason}]);
}];
return;
}
image = [self fixOrientation:image]; // Rotate the image for upload to web
// If needed, downscale image
float maxWidth = image.size.width;
float maxHeight = image.size.height;
if ([self.options valueForKey:@"maxWidth"]) {
maxWidth = [[self.options valueForKey:@"maxWidth"] floatValue];
}
if ([self.options valueForKey:@"maxHeight"]) {
maxHeight = [[self.options valueForKey:@"maxHeight"] floatValue];
}
image = [self downscaleImageIfNecessary:image maxWidth:maxWidth maxHeight:maxHeight];
NSData *data;
if ([[[self.options objectForKey:@"imageFileType"] stringValue] isEqualToString:@"png"]) {
data = UIImagePNGRepresentation(image);
}
else {
data = UIImageJPEGRepresentation(image, [[self.options valueForKey:@"quality"] floatValue]);
}
[data writeToFile:path atomically:YES];
if (![[self.options objectForKey:@"noData"] boolValue]) {
NSString *dataString = [data base64EncodedStringWithOptions:0]; // base64 encoded image string
[self.response setObject:dataString forKey:@"data"];
}
BOOL vertical = (image.size.width < image.size.height) ? YES : NO;
[self.response setObject:@(vertical) forKey:@"isVertical"];
NSURL *fileURL = [NSURL fileURLWithPath:path];
NSString *filePath = [fileURL absoluteString];
[self.response setObject:filePath forKey:@"uri"];
// add ref to the original image
NSString *origURL = [imageURL absoluteString];
if (origURL) {
[self.response setObject:origURL forKey:@"origURL"];
}
NSNumber *fileSizeValue = nil;
NSError *fileSizeError = nil;
[fileURL getResourceValue:&fileSizeValue forKey:NSURLFileSizeKey error:&fileSizeError];
if (fileSizeValue){
[self.response setObject:fileSizeValue forKey:@"fileSize"];
}
[self.response setObject:@(image.size.width) forKey:@"width"];
[self.response setObject:@(image.size.height) forKey:@"height"];
NSDictionary *storageOptions = [self.options objectForKey:@"storageOptions"];
if (storageOptions && [[storageOptions objectForKey:@"cameraRoll"] boolValue] == YES && self.picker.sourceType == UIImagePickerControllerSourceTypeCamera) {
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
if ([[storageOptions objectForKey:@"waitUntilSaved"] boolValue]) {
[library writeImageToSavedPhotosAlbum:image.CGImage metadata:[info valueForKey:UIImagePickerControllerMediaMetadata] completionBlock:^(NSURL *assetURL, NSError *error) {
if (error) {
NSLog(@"Error while saving picture into photo album");
} else {
// when the image has been saved in the photo album
if (assetURL) {
PHAsset *capturedAsset = [PHAsset fetchAssetsWithALAssetURLs:@[assetURL] options:nil].lastObject;
NSString *originalFilename = [self originalFilenameForAsset:capturedAsset assetType:PHAssetResourceTypePhoto];
self.response[@"fileName"] = originalFilename ?: [NSNull null];
// This implementation will never have a location for the captured image, it needs to be added manually with CoreLocation code here.
if (capturedAsset.creationDate) {
self.response[@"timestamp"] = [[ImagePickerManager ISO8601DateFormatter] stringFromDate:capturedAsset.creationDate];
}
}
self.callback(@[self.response]);
}
}];
} else {
[library writeImageToSavedPhotosAlbum:image.CGImage metadata:[info valueForKey:UIImagePickerControllerMediaMetadata] completionBlock:nil];
}
}
}
else { // VIDEO
NSURL *videoRefURL = info[UIImagePickerControllerReferenceURL];
NSURL *videoURL = info[UIImagePickerControllerMediaURL];
NSURL *videoDestinationURL = [NSURL fileURLWithPath:path];
if (videoRefURL) {
PHAsset *pickedAsset = [PHAsset fetchAssetsWithALAssetURLs:@[videoRefURL] options:nil].lastObject;
NSString *originalFilename = [self originalFilenameForAsset:pickedAsset assetType:PHAssetResourceTypeVideo];
self.response[@"fileName"] = originalFilename ?: [NSNull null];
if (pickedAsset.location) {
self.response[@"latitude"] = @(pickedAsset.location.coordinate.latitude);
self.response[@"longitude"] = @(pickedAsset.location.coordinate.longitude);
}
if (pickedAsset.creationDate) {
self.response[@"timestamp"] = [[ImagePickerManager ISO8601DateFormatter] stringFromDate:pickedAsset.creationDate];
}
}
if ([videoURL.URLByResolvingSymlinksInPath.path isEqualToString:videoDestinationURL.URLByResolvingSymlinksInPath.path] == NO) {
NSFileManager *fileManager = [NSFileManager defaultManager];
// Delete file if it already exists
if ([fileManager fileExistsAtPath:videoDestinationURL.path]) {
[fileManager removeItemAtURL:videoDestinationURL error:nil];
}
if (videoURL) { // Protect against reported crash
NSError *error = nil;
[fileManager moveItemAtURL:videoURL toURL:videoDestinationURL error:&error];
if (error) {
self.callback(@[@{@"error": error.localizedFailureReason}]);
return;
}
}
}
[self.response setObject:videoDestinationURL.absoluteString forKey:@"uri"];
if (videoRefURL.absoluteString) {
[self.response setObject:videoRefURL.absoluteString forKey:@"origURL"];
}
NSDictionary *storageOptions = [self.options objectForKey:@"storageOptions"];
if (storageOptions && [[storageOptions objectForKey:@"cameraRoll"] boolValue] == YES && self.picker.sourceType == UIImagePickerControllerSourceTypeCamera) {
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
[library writeVideoAtPathToSavedPhotosAlbum:videoDestinationURL completionBlock:^(NSURL *assetURL, NSError *error) {
if (error) {
self.callback(@[@{@"error": error.localizedFailureReason}]);
return;
} else {
NSLog(@"Save video succeed.");
if ([[storageOptions objectForKey:@"waitUntilSaved"] boolValue]) {
if (assetURL) {
PHAsset *capturedAsset = [PHAsset fetchAssetsWithALAssetURLs:@[assetURL] options:nil].lastObject;
NSString *originalFilename = [self originalFilenameForAsset:capturedAsset assetType:PHAssetResourceTypeVideo];
self.response[@"fileName"] = originalFilename ?: [NSNull null];
// This implementation will never have a location for the captured image, it needs to be added manually with CoreLocation code here.
if (capturedAsset.creationDate) {
self.response[@"timestamp"] = [[ImagePickerManager ISO8601DateFormatter] stringFromDate:capturedAsset.creationDate];
}
}
self.callback(@[self.response]);
}
}
}];
}
}
// If storage options are provided, check the skipBackup flag
if ([self.options objectForKey:@"storageOptions"] && [[self.options objectForKey:@"storageOptions"] isKindOfClass:[NSDictionary class]]) {
NSDictionary *storageOptions = [self.options objectForKey:@"storageOptions"];
if ([[storageOptions objectForKey:@"skipBackup"] boolValue]) {
[self addSkipBackupAttributeToItemAtPath:path]; // Don't back up the file to iCloud
}
if ([[storageOptions objectForKey:@"waitUntilSaved"] boolValue] == NO ||
[[storageOptions objectForKey:@"cameraRoll"] boolValue] == NO ||
self.picker.sourceType != UIImagePickerControllerSourceTypeCamera)
{
self.callback(@[self.response]);
}
}
else {
self.callback(@[self.response]);
}
};
dispatch_async(dispatch_get_main_queue(), ^{
[picker dismissViewControllerAnimated:YES completion:dismissCompletionBlock];
});
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
dispatch_async(dispatch_get_main_queue(), ^{
[picker dismissViewControllerAnimated:YES completion:^{
self.callback(@[@{@"didCancel": @YES}]);
}];
});
}
#pragma mark - Helpers
- (void)checkCameraPermissions:(void(^)(BOOL granted))callback
{
AVAuthorizationStatus status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
if (status == AVAuthorizationStatusAuthorized) {
callback(YES);
return;
} else if (status == AVAuthorizationStatusNotDetermined){
[AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
callback(granted);
return;
}];
} else {
callback(NO);
}
}
- (void)checkPhotosPermissions:(void(^)(BOOL granted))callback
{
PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
if (status == PHAuthorizationStatusAuthorized) {
callback(YES);
return;
} else if (status == PHAuthorizationStatusNotDetermined) {
[PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
if (status == PHAuthorizationStatusAuthorized) {
callback(YES);
return;
}
else {
callback(NO);
return;
}
}];
}
else {
callback(NO);
}
}
- (UIImage*)downscaleImageIfNecessary:(UIImage*)image maxWidth:(float)maxWidth maxHeight:(float)maxHeight
{
UIImage* newImage = image;
// Nothing to do here
if (image.size.width <= maxWidth && image.size.height <= maxHeight) {
return newImage;
}
CGSize scaledSize = CGSizeMake(image.size.width, image.size.height);
if (maxWidth < scaledSize.width) {
scaledSize = CGSizeMake(maxWidth, (maxWidth / scaledSize.width) * scaledSize.height);
}
if (maxHeight < scaledSize.height) {
scaledSize = CGSizeMake((maxHeight / scaledSize.height) * scaledSize.width, maxHeight);
}
// If the pixels are floats, it causes a white line in iOS8 and probably other versions too
scaledSize.width = (int)scaledSize.width;
scaledSize.height = (int)scaledSize.height;
UIGraphicsBeginImageContext(scaledSize); // this will resize
[image drawInRect:CGRectMake(0, 0, scaledSize.width, scaledSize.height)];
newImage = UIGraphicsGetImageFromCurrentImageContext();
if (newImage == nil) {
NSLog(@"could not scale image");
}
UIGraphicsEndImageContext();
return newImage;
}
- (UIImage *)fixOrientation:(UIImage *)srcImg {
if (srcImg.imageOrientation == UIImageOrientationUp) {
return srcImg;
}
CGAffineTransform transform = CGAffineTransformIdentity;
switch (srcImg.imageOrientation) {
case UIImageOrientationDown:
case UIImageOrientationDownMirrored:
transform = CGAffineTransformTranslate(transform, srcImg.size.width, srcImg.size.height);
transform = CGAffineTransformRotate(transform, M_PI);
break;
case UIImageOrientationLeft:
case UIImageOrientationLeftMirrored:
transform = CGAffineTransformTranslate(transform, srcImg.size.width, 0);
transform = CGAffineTransformRotate(transform, M_PI_2);
break;
case UIImageOrientationRight:
case UIImageOrientationRightMirrored:
transform = CGAffineTransformTranslate(transform, 0, srcImg.size.height);
transform = CGAffineTransformRotate(transform, -M_PI_2);
break;
case UIImageOrientationUp:
case UIImageOrientationUpMirrored:
break;
}
switch (srcImg.imageOrientation) {
case UIImageOrientationUpMirrored:
case UIImageOrientationDownMirrored:
transform = CGAffineTransformTranslate(transform, srcImg.size.width, 0);
transform = CGAffineTransformScale(transform, -1, 1);
break;
case UIImageOrientationLeftMirrored:
case UIImageOrientationRightMirrored:
transform = CGAffineTransformTranslate(transform, srcImg.size.height, 0);
transform = CGAffineTransformScale(transform, -1, 1);
break;
case UIImageOrientationUp:
case UIImageOrientationDown:
case UIImageOrientationLeft:
case UIImageOrientationRight:
break;
}
CGContextRef ctx = CGBitmapContextCreate(NULL, srcImg.size.width, srcImg.size.height, CGImageGetBitsPerComponent(srcImg.CGImage), 0, CGImageGetColorSpace(srcImg.CGImage), CGImageGetBitmapInfo(srcImg.CGImage));
CGContextConcatCTM(ctx, transform);
switch (srcImg.imageOrientation) {
case UIImageOrientationLeft:
case UIImageOrientationLeftMirrored:
case UIImageOrientationRight:
case UIImageOrientationRightMirrored:
CGContextDrawImage(ctx, CGRectMake(0,0,srcImg.size.height,srcImg.size.width), srcImg.CGImage);
break;
default:
CGContextDrawImage(ctx, CGRectMake(0,0,srcImg.size.width,srcImg.size.height), srcImg.CGImage);
break;
}
CGImageRef cgimg = CGBitmapContextCreateImage(ctx);
UIImage *img = [UIImage imageWithCGImage:cgimg];
CGContextRelease(ctx);
CGImageRelease(cgimg);
return img;
}
- (BOOL)addSkipBackupAttributeToItemAtPath:(NSString *) filePathString
{
NSURL* URL= [NSURL fileURLWithPath: filePathString];
if ([[NSFileManager defaultManager] fileExistsAtPath: [URL path]]) {
NSError *error = nil;
BOOL success = [URL setResourceValue: [NSNumber numberWithBool: YES]
forKey: NSURLIsExcludedFromBackupKey error: &error];
if(!success){
NSLog(@"Error excluding %@ from backup %@", [URL lastPathComponent], error);
}
return success;
}
else {
NSLog(@"Error setting skip backup attribute: file not found");
return @NO;
}
}
-(BOOL)showPermissionAlert{
NSDictionary *permissionDenied = [self.options objectForKey:@"permissionDenied"];
if(!permissionDenied){
return NO;
}
NSString *title = [permissionDenied objectForKey:@"title"];
NSString *text = [permissionDenied objectForKey:@"text"];
NSString *settingTitle = [permissionDenied objectForKey:@"settingTitle"];
NSString *okTitle = [permissionDenied objectForKey:@"okTitle"];
UIAlertController *alert = [UIAlertController alertControllerWithTitle:title message:text preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:okTitle style:UIAlertActionStyleCancel handler:nil];
UIAlertAction *openSettingAction = [UIAlertAction actionWithTitle:settingTitle style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
if([[UIApplication sharedApplication] canOpenURL: [NSURL URLWithString:UIApplicationOpenSettingsURLString]]){
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
}else{
NSLog(@"The application cannot open Settings for unknow reasons");
}
}];
[alert addAction:cancelAction];
[alert addAction:openSettingAction];
[[[UIApplication sharedApplication].delegate.window rootViewController] presentViewController:alert animated:YES completion:nil];
return YES;
}
#pragma mark - Class Methods
+ (NSDateFormatter * _Nonnull)ISO8601DateFormatter {
static NSDateFormatter *ISO8601DateFormatter;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
ISO8601DateFormatter = [[NSDateFormatter alloc] init];
NSLocale *enUSPOSIXLocale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];
ISO8601DateFormatter.locale = enUSPOSIXLocale;
ISO8601DateFormatter.timeZone = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];
ISO8601DateFormatter.dateFormat = @"yyyy-MM-dd'T'HH:mm:ssZZZZZ";
});
return ISO8601DateFormatter;
}
@end