JLChen
2021-08-02 38f4fb064df09f344fc3237409c76a9fba2a8a9e
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
/*
 * Copyright (c) 2010-2020 Belledonne Communications SARL.
 *
 * This file is part of linphone-iphone
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
 
#import <MobileCoreServices/UTCoreTypes.h>
#import "ImagePickerView.h"
#import "PhoneMainView.h"
#import "SVProgressHUD.h"
#import "ShareViewController.h"
 
 
@implementation ImagePickerView
 
@synthesize imagePickerDelegate;
@synthesize sourceType;
@synthesize mediaTypes;
@synthesize allowsEditing;
@synthesize popoverController;
 
#pragma mark - Lifecycle Functions
 
- (id)init {
    self = [super init];
    if (self != nil) {
        pickerController = [[UIImagePickerController alloc] init];
        if (IPAD) {
            popoverController = [[UIPopoverController alloc] initWithContentViewController:pickerController];
        }
    }
    return self;
}
 
- (BOOL) shouldAutorotate{
    return NO;
}
 
#if __IPHONE_OS_VERSION_MAX_ALLOWED < 90000
- (NSUInteger)supportedInterfaceOrientations {
    return UIInterfaceOrientationMaskPortrait;
}
#else
- (UIInterfaceOrientationMask)supportedInterfaceOrientations{
    return UIInterfaceOrientationMaskPortrait;
}
#endif
 
#pragma mark - UICompositeViewDelegate Functions
 
static UICompositeViewDescription *compositeDescription = nil;
 
+ (UICompositeViewDescription *)compositeViewDescription {
    if (compositeDescription == nil) {
        compositeDescription = [[UICompositeViewDescription alloc] init:self.class
                                                              statusBar:StatusBarView.class
                                                                 tabBar:nil
                                                               sideMenu:SideMenuView.class
                                                             fullscreen:false
                                                         isLeftFragment:NO
                                                           fragmentWith:nil];
        compositeDescription.darkBackground = false;
    }
    return compositeDescription;
}
 
- (UICompositeViewDescription *)compositeViewDescription {
    return self.class.compositeViewDescription;
}
 
#pragma mark - ViewController Functions
 
- (void)viewDidLoad {
    [super viewDidLoad];
 
    [self.view setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight];
    if (popoverController == nil) {
        [pickerController.view setFrame:[self.view bounds]];
        [self.view addSubview:[pickerController view]];
    } else {
        [popoverController setDelegate:self];
    }
    [pickerController setDelegate:self];
}
 
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    if (popoverController != nil) {
        [popoverController presentPopoverFromRect:CGRectZero
                                           inView:self.view
                         permittedArrowDirections:UIPopoverArrowDirectionAny
                                         animated:FALSE];
    }
    [[UIApplication sharedApplication] setStatusBarHidden:NO]; // Fix UIImagePickerController status bar hide
    [[UIApplication sharedApplication]
        setStatusBarStyle:UIStatusBarStyleDefault]; // Fix UIImagePickerController status bar style change
 
    [PhoneMainView.instance hideStatusBar:YES];
    
    //Prevent rotation of camera
    NSNumber *value = [NSNumber numberWithInt:UIInterfaceOrientationPortrait];
    [[UIDevice currentDevice] setValue:value forKey:@"orientation"];
}
 
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    if (popoverController != nil) {
        [popoverController dismissPopoverAnimated:NO];
    }
 
    [PhoneMainView.instance hideStatusBar:NO];
}
 
#pragma mark - Property Functions
 
- (BOOL)allowsEditing {
    return pickerController.allowsEditing;
}
 
- (void)setAllowsEditing:(BOOL)aallowsEditing {
    pickerController.allowsEditing = aallowsEditing;
}
 
- (UIImagePickerControllerSourceType)sourceType {
    return pickerController.sourceType;
}
 
- (void)setSourceType:(UIImagePickerControllerSourceType)asourceType {
    pickerController.sourceType = asourceType;
}
 
- (NSArray *)mediaTypes {
    return pickerController.mediaTypes;
}
 
- (void)setMediaTypes:(NSArray *)amediaTypes {
    pickerController.mediaTypes = amediaTypes;
}
 
#pragma mark -
 
- (void)dismiss {
    if ([[PhoneMainView.instance currentView] equal:ImagePickerView.compositeViewDescription]) {
        [PhoneMainView.instance popCurrentView];
    }
}
 
#pragma mark - UIImagePickerControllerDelegate Functions
 
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    
    dispatch_async(dispatch_get_main_queue(), ^{
        
        [self dismiss];
        
        NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
        if ([type isEqualToString:(NSString *)kUTTypeVideo] ||
            [type isEqualToString:(NSString *)kUTTypeMovie]) {
            NSURL *urlvideo = [info objectForKey:UIImagePickerControllerMediaURL];
            if(urlvideo != nil && self.imagePickerDelegate != nil) {
                [imagePickerDelegate imagePickerDelegateVideo:urlvideo info:info];
            }
        } else {
            NSURL *alassetURL = [info objectForKey:UIImagePickerControllerReferenceURL];
            PHAsset *phasset = nil;
            // when photo from camera, it hasn't be saved
            if (alassetURL) {
                PHFetchResult<PHAsset *> *phFetchResult = [PHAsset fetchAssetsWithALAssetURLs:@[alassetURL] options:nil];
                phasset = [phFetchResult firstObject];
            }
            
            UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage] ? [info objectForKey:UIImagePickerControllerEditedImage] : [info objectForKey:UIImagePickerControllerOriginalImage];
            if (!phasset) {
                [self writeImageToGallery:image];
                return;
            }
            [self passImageToDelegate:image PHAssetId:[phasset localIdentifier]];
        }
    });
    
}
 
 
-(void) writeImageToGallery:(UIImage *)image {
    NSString *localIdentifier;
    [SVProgressHUD show];
    
    PHFetchResult<PHAssetCollection *> *assetCollections = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];
    __block PHObjectPlaceholder *placeHolder;
 
    for (PHAssetCollection *assetCollection in assetCollections) {
        if([[assetCollection localizedTitle] isEqualToString:[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleDisplayName"]]  ){
            localIdentifier = assetCollection.localIdentifier;
            break;
        }
    }
    
    if(localIdentifier ){
        PHFetchResult *fetchResult = [PHAssetCollection fetchAssetCollectionsWithLocalIdentifiers:@[localIdentifier] options:nil];
        PHAssetCollection *assetCollection = fetchResult.firstObject;
 
        [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
            PHAssetChangeRequest *assetChangeRequest = [PHAssetChangeRequest creationRequestForAssetFromImage:image];
            PHAssetCollectionChangeRequest *assetCollectionChangeRequest = [PHAssetCollectionChangeRequest changeRequestForAssetCollection:assetCollection];
            [assetCollectionChangeRequest addAssets:@[[assetChangeRequest placeholderForCreatedAsset]]];
            placeHolder = [assetChangeRequest placeholderForCreatedAsset];
        } completionHandler:^(BOOL success, NSError *error) {
            dispatch_async(dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
            if (!success) {
                NSLog(@"Error creating asset: %@", error);
            } else {
                [self passImageToDelegate:image PHAssetId:[placeHolder localIdentifier]];
            }
            });
        }];
    }else{
        __block PHObjectPlaceholder *albumPlaceholder;
        [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
            PHAssetCollectionChangeRequest *changeRequest = [PHAssetCollectionChangeRequest creationRequestForAssetCollectionWithTitle:[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleDisplayName"]];
            albumPlaceholder = changeRequest.placeholderForCreatedAssetCollection;
        } completionHandler:^(BOOL success, NSError *error) {
            if (success) {
                PHFetchResult *fetchResult = [PHAssetCollection fetchAssetCollectionsWithLocalIdentifiers:@[albumPlaceholder.localIdentifier] options:nil];
                PHAssetCollection *assetCollection = fetchResult.firstObject;
                
                [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
                    PHAssetChangeRequest *assetChangeRequest = [PHAssetChangeRequest creationRequestForAssetFromImage:image];
                    PHAssetCollectionChangeRequest *assetCollectionChangeRequest = [PHAssetCollectionChangeRequest changeRequestForAssetCollection:assetCollection];
                    [assetCollectionChangeRequest addAssets:@[[assetChangeRequest placeholderForCreatedAsset]]];
                    placeHolder = [assetChangeRequest placeholderForCreatedAsset];
                } completionHandler:^(BOOL success, NSError *error) {
                    dispatch_async(dispatch_get_main_queue(), ^{
 
                    [SVProgressHUD dismiss];
                    if (!success) {
                        NSLog(@"Error creating asset: %@", error);
                    } else {
                        [self passImageToDelegate:image PHAssetId:[placeHolder localIdentifier]];
                    }
                    });
                }];
            } else {
                [SVProgressHUD dismiss];
                NSLog(@"Error creating album: %@", error);
            }
        }];
        
    }
}
 
 
- (void) passImageToDelegate:(UIImage *)image PHAssetId:(NSString *)assetId {
    if (imagePickerDelegate != nil) {
        [imagePickerDelegate imagePickerDelegateImage:image info:(NSString *)assetId];
    }
}
/*
    if (imagePickerDelegate != nil) {
        [imagePickerDelegate imagePickerDelegateImage:image info:(__bridge NSDictionary *)contextInfo];
    }
}
*/
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [self dismiss];
}
 
- (BOOL)popoverControllerShouldDismissPopover:(UIPopoverController *)apopoverController {
    [self dismiss];
    return TRUE;
}
 
- (void)navigationController:(UINavigationController *)navigationController
      willShowViewController:(UIViewController *)viewController
                    animated:(BOOL)animated {
 
    if ([navigationController isKindOfClass:[UIImagePickerController class]]) {
        [[UIApplication sharedApplication] setStatusBarHidden:NO]; // Fix UIImagePickerController status bar hide
        [[UIApplication sharedApplication]
            setStatusBarStyle:UIStatusBarStyleBlackOpaque]; // Fix UIImagePickerController status bar style change
    }
}
 
+ (void)SelectImageFromDevice:(id<ImagePickerDelegate>)delegate
                   atPosition:(UIView *)ipadPopoverView
                       inView:(UIView *)ipadView
     withDocumentMenuDelegate:(id<UIDocumentMenuDelegate>)documentMenuDelegate {
    void (^block)(UIImagePickerControllerSourceType) = ^(UIImagePickerControllerSourceType type) {
      ImagePickerView *view = VIEW(ImagePickerView);
      view.sourceType = type;
 
      // Displays a control that allows the user to choose picture or
      // movie capture, if both are available:
      view.mediaTypes = [NSArray arrayWithObjects:(NSString *)kUTTypeMovie,(NSString *)kUTTypeImage,nil];
 
      // Hides the controls for moving & scaling pictures, or for
      // trimming movies. To instead show the controls, use YES.
      view.allowsEditing = NO;
      view.imagePickerDelegate = delegate;
 
      if (IPAD && ipadView && ipadPopoverView) {
          UIView *iterview = ipadPopoverView;
          CGRect ipadPopoverPosition = iterview.frame;
          do {
              ipadPopoverPosition =
                  [iterview.superview convertRect:ipadPopoverPosition toView:iterview.superview.superview];
              iterview = iterview.superview;
          } while (iterview && iterview.superview != ipadView);
          [view.popoverController presentPopoverFromRect:ipadPopoverPosition
                                                  inView:ipadView
                                permittedArrowDirections:UIPopoverArrowDirectionAny
                                                animated:FALSE];
      } else {
          [PhoneMainView.instance changeCurrentView:view.compositeViewDescription];
      }
    };
    if ([PHPhotoLibrary authorizationStatus] == PHAuthorizationStatusAuthorized) {
        DTActionSheet *sheet = [[DTActionSheet alloc] initWithTitle:NSLocalizedString(@"Select the source", nil)];
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            [sheet addButtonWithTitle:NSLocalizedString(@"Camera", nil)
                                block:^() {
                                    if([AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo] !=  AVAuthorizationStatusAuthorized ) {
                                        [[[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Camera's permission", nil) message:NSLocalizedString(@"Camera not authorized", nil) delegate:nil cancelButtonTitle:nil otherButtonTitles:@"Continue", nil] show];
                                        return;
                                    }
                                    block(UIImagePickerControllerSourceTypeCamera);
                                }];
        }
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
            [sheet addButtonWithTitle:NSLocalizedString(@"Photo library", nil)
                                block:^() {
                                    block(UIImagePickerControllerSourceTypePhotoLibrary);
                                }];
        }
        
        if (documentMenuDelegate) {
            [sheet addButtonWithTitle:NSLocalizedString(@"Document",nil) block:^(){
                [self pickDocumentForDelegate:documentMenuDelegate];
            }];
        }
        [sheet addCancelButtonWithTitle:NSLocalizedString(@"Cancel", nil) block:nil];
        
        [sheet showInView:PhoneMainView.instance.view];
    } else {
        [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
            dispatch_async(dispatch_get_main_queue(), ^{
                if ([PHPhotoLibrary authorizationStatus] == PHAuthorizationStatusAuthorized) {
                    DTActionSheet *sheet = [[DTActionSheet alloc] initWithTitle:NSLocalizedString(@"Select the source", nil)];
                    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
                        [sheet addButtonWithTitle:NSLocalizedString(@"Camera", nil)
                                            block:^() {
                                                if([AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo] !=  AVAuthorizationStatusAuthorized ) {
                                                    [[[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Camera's permission", nil) message:NSLocalizedString(@"Camera not authorized", nil) delegate:nil cancelButtonTitle:nil otherButtonTitles:@"Continue", nil] show];
                                                    return;
                                                }
                                                block(UIImagePickerControllerSourceTypeCamera);
                                            }];
                    }
                    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
                        [sheet addButtonWithTitle:NSLocalizedString(@"Photo library", nil)
                                            block:^() {
                                                block(UIImagePickerControllerSourceTypePhotoLibrary);
                                            }];
                    }
                    if (documentMenuDelegate) {
                        [sheet addButtonWithTitle:NSLocalizedString(@"Document",nil) block:^(){
                            [self pickDocumentForDelegate:documentMenuDelegate];
                        }];
                    }
                    [sheet addCancelButtonWithTitle:NSLocalizedString(@"Cancel", nil) block:nil];
                    
                    [sheet showInView:PhoneMainView.instance.view];
                } else {
                    [[[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Photo's permission", nil) message:NSLocalizedString(@"Photo not authorized", nil) delegate:nil cancelButtonTitle:nil otherButtonTitles:@"Continue", nil] show];
                }
            });
        }];
    }
}
 
+(void) pickDocumentForDelegate:(id<UIDocumentMenuDelegate>)documentMenuDelegate {
    UIDocumentMenuViewController *documentProviderMenu = [[UIDocumentMenuViewController alloc] initWithDocumentTypes:SUPPORTED_EXTENTIONS inMode:UIDocumentPickerModeImport];
    documentProviderMenu.delegate = documentMenuDelegate;
    if (IPAD) {
        /* On iPad the activity view controller will be displayed as a popover using the new UIPopoverPresentationController, it requires that you specify an anchor point for the presentation of the popover using one of the three following properties: barButtonItem, sourceView, sourceRect */
        ChatConversationView *chatView = VIEW(ChatConversationView);
        documentProviderMenu.popoverPresentationController.sourceView = chatView.view;
        CGRect frame = documentProviderMenu.popoverPresentationController.sourceRect;
        CGRect topBarFrame = chatView.topBar.frame;
        documentProviderMenu.popoverPresentationController.sourceRect = CGRectMake(topBarFrame.origin.x + topBarFrame.size.width/2, topBarFrame.origin.y + topBarFrame.size.height, frame.size.width, frame.size.height);
    }
    dispatch_async(dispatch_get_main_queue(), ^ {
        [PhoneMainView.instance presentViewController:documentProviderMenu animated:YES completion:nil];
    });
}
 
@end