PhotoActionSheetView.m 19.1 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
//
//  PhotoActionSheetView.m
//  IM_ios_client
//
//  Created by 赵世强 on 16/5/31.
//  Copyright © 2016年 xiniu. All rights reserved.
//

#import "PhotoActionSheetView.h"
#import <Photos/Photos.h>
#import "SelectPhotoModel.h"
#import "SelectCollectionCell.h"
#import "ZLPhotoBrowser.h"
#import "ZLShowBigImgViewController.h"
#import "ZLAnimationTool.h"
#import "ZLDefine.h"
#import "ZLPhotoTool.h"
#import "ToastUtils.h"
//#import "ZZPhotoKit.h"
//#import "ZZPhotoDatas.h"
#import "Masonry.h"



typedef void (^handler)(NSArray<UIImage *> *selectPhotos);

@interface PhotoActionSheetView () <UICollectionViewDelegateFlowLayout, UIImagePickerControllerDelegate, UINavigationControllerDelegate, PHPhotoLibraryChangeObserver,UITableViewDelegate,UITableViewDataSource,UICollectionViewDelegate,UICollectionViewDataSource>

{
    NSArray *arr_click;
    CGPoint fromPoint;
    UITableView *table;
    BOOL isSure;
}

@property (nonatomic, assign) BOOL animate;
@property (nonatomic, strong) NSMutableArray<PHAsset *> *arrayDataSources;
@property (nonatomic, strong) NSMutableArray *arraySelectPhotos;
@property (nonatomic, copy) handler handler;
//@property(strong,nonatomic) ZZPhotoDatas     *datas;

@end

@implementation PhotoActionSheetView

- (instancetype)init
{
    self = [super init];
    if (self) {

        
        self.baseView = [[UIView alloc]init];
        
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        layout.minimumInteritemSpacing = 3;
        layout.sectionInset = UIEdgeInsetsMake(0, 5, 0, 5);
        
        self.collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, [[UIScreen mainScreen] bounds].size.width, 155) collectionViewLayout:layout];
        self.collectionView.backgroundColor = [UIColor whiteColor];
        self.collectionView.delegate = self;
        self.collectionView.dataSource = self;
        self.collectionView.showsVerticalScrollIndicator = NO;
        [self.collectionView registerClass:[SelectCollectionCell class] forCellWithReuseIdentifier:@"SelectCollectionCell"];
        
        table = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStylePlain];
        table.delegate = self;
        table.dataSource = self;
//        tableView.scrollEnabled = NO;
        table.tableHeaderView = self.collectionView;
        [self addSubview:table];
        [table mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(self.mas_bottom);
            make.width.equalTo(self.mas_width);
            make.left.equalTo(self.mas_left);
            make.height.equalTo(@(574));
        }];
        
        
//        _maxSelectCount = 10;
        _maxPreviewCount = 20;
        isSure = NO;
        _arrayDataSources  = [NSMutableArray array];
        _arraySelectPhotos = [NSMutableArray array];
        arr_click = @[@"拍照",@"相册",@"取消"];
        //注册实施监听相册变化
        [[PHPhotoLibrary sharedPhotoLibrary] registerChangeObserver:self];
    }
    return self;
}

- (void)showWithSender:(UIViewController *)sender animate:(BOOL)animate completion:(void (^)(NSArray<UIImage *> *))completion
{
    if (![self judgeIsHavePhotoAblumAuthority]) {
        
    }
    
    _handler = completion;
    _animate = animate;
    _sender  = sender;
    
    [self loadPhotoFromAlbum];
    
    [self show];
}

//相册变化回调
- (void)photoLibraryDidChange:(PHChange *)changeInstance
{
    dispatch_sync(dispatch_get_main_queue(), ^{
        [self loadPhotoFromAlbum];
    });
}

- (void)loadPhotoFromAlbum
{
    [_arrayDataSources removeAllObjects];
    
    // 获取所有资源的集合,并按资源的创建时间排序
    PHFetchOptions *options = [[PHFetchOptions alloc] init];
    options.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:YES]];
    PHFetchResult *assetsFetchResults = [PHAsset fetchAssetsWithOptions:options];
    [assetsFetchResults enumerateObjectsUsingBlock:^(PHAssetCollection * _Nonnull collection, NSUInteger idx, BOOL *stop) {
        if (idx <self.maxSelectCount) {
            [_arrayDataSources addObject:(PHAsset *)collection];
        }
        
    }];
    
    [self.collectionView reloadData];
}

#pragma mark - 判断软件是否有相册、相机访问权限
- (BOOL)judgeIsHavePhotoAblumAuthority
{
    PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
    if (status == PHAuthorizationStatusRestricted ||
        status == PHAuthorizationStatusDenied) {
        return NO;
    }
    return YES;
}

- (BOOL)judgeIsHaveCameraAuthority
{
    AVAuthorizationStatus status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (status == AVAuthorizationStatusRestricted ||
        status == AVAuthorizationStatusDenied) {
        return NO;
    }
    return YES;
}

- (void)show
{
    
    [self.sender.view addSubview:self];
    [self mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.sender.view);
//        self.frame = CGRectMake(0, 0, ScreenWidth, ScreenHeight - 64);
    }];
    
    [self resetSubViewState];
    
    if (_animate) {
        fromPoint = CGPointMake(kViewWidth/2, kViewHeight+kBaseViewHeight/2);
        CGPoint toPoint   = CGPointMake(kViewWidth/2, kViewHeight-kBaseViewHeight/2);
        CABasicAnimation *animation = [ZLAnimationTool animateWithFromValue:[NSValue valueWithCGPoint:fromPoint] toValue:[NSValue valueWithCGPoint:toPoint] duration:0.2 keyPath:@"position"];
        [self.baseView.layer addAnimation:animation forKey:nil];
    }
}

#pragma mark - 显示隐藏视图及相关动画
- (void)resetSubViewState
{
    self.hidden = NO;
    [self.arraySelectPhotos removeAllObjects];
    [self.collectionView setContentOffset:CGPointZero];
}

#pragma maek - UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 3;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"myCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    if (!isSure) {
        cell.textLabel.text = arr_click[indexPath.row];
    }else
    {
        if (indexPath.row == 0) {
            cell.textLabel.text = [NSString stringWithFormat:@"确定(%ld)", (unsigned long)_arraySelectPhotos.count];
        }else
        {
            cell.textLabel.text = arr_click[indexPath.row];
        }
    }
    cell.textLabel.textAlignment = NSTextAlignmentCenter;
    return cell;    
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    if (indexPath.row == 0) {
        if (!isSure) {
            if (_arraySelectPhotos.count > 0) {
                [self done];
                [self hide];
            } else {
                if (![self judgeIsHaveCameraAuthority]) {
                    [self showAlertWithTitle:@"无法使用相机" message:@"请在iPhone的\"设置-隐私-相机\"中允许访问相机"];
                    [self hide];
                    return;
                }
                //拍照
                if ([UIImagePickerController isSourceTypeAvailable:
                     UIImagePickerControllerSourceTypeCamera])
                {
                    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
                    picker.delegate = self;
                    picker.allowsEditing = NO;
                    picker.videoQuality = UIImagePickerControllerQualityTypeLow;
                    picker.sourceType = UIImagePickerControllerSourceTypeCamera;
                    [self.sender presentViewController:picker animated:YES completion:^{
                    }];
                    picker = nil;
                }
            }
        }else
        {
            //  TODO:发送请求
            [self done];
            [self hide];
        }
    }else if (indexPath.row == 1) {
        if (![self judgeIsHavePhotoAblumAuthority]) {
            //无相册访问权限

        } else {
            
            ZZPhotoController *photoController = [[ZZPhotoController alloc]init];
            photoController.photoPickerController.selectArray = _arraySelectPhotos;
            photoController.selectPhotoOfMax = self.maxSelectCount;
            __weak typeof(PhotoActionSheetView *) weakSelf = self;
            [photoController showIn:self.sender.navigationController result:^(id responseObject){
                
                NSArray *array = (NSArray *)responseObject;
                NSLog(@"%@",responseObject);
                [weakSelf.arraySelectPhotos removeAllObjects];
                [weakSelf.arraySelectPhotos addObjectsFromArray:array];
                [weakSelf done];
                [weakSelf hide];

                
            }];
           
//            self.baseView.hidden = YES;
//            _animate = NO;
//            
//            ZLPhotoBrowser *photoBrowser = [[ZLPhotoBrowser alloc] initWithStyle:UITableViewStylePlain];
//            
//            photoBrowser.maxSelectCount = self.maxSelectCount;
//            photoBrowser.arraySelectPhotos = _arraySelectPhotos.mutableCopy;
//            
//
//            [photoBrowser setDoneBlock:^(NSArray<SelectPhotoModel *> *selectPhotos) {
//                [weakSelf.arraySelectPhotos removeAllObjects];
//                [weakSelf.arraySelectPhotos addObjectsFromArray:selectPhotos];
//                [weakSelf done];
//                [weakSelf hide];
//            }];
//            [photoBrowser setCancelBlock:^{
//                [weakSelf hide];
//            }];
//            
//            [self.sender.navigationController.view.layer addAnimation:[ZLAnimationTool animateWithType:kCATransitionMoveIn subType:kCATransitionFromTop duration:0.25] forKey:nil];
//            self.sender.hidesBottomBarWhenPushed = YES;
//            [self.sender.navigationController pushViewController:photoBrowser animated:NO];

        }
    }else if (indexPath.row == 2) {
        [_arraySelectPhotos removeAllObjects];
        [self hide];
    }
}

- (void)showAlertWithTitle:(NSString *)title message:(NSString *)message
{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
    [alert addAction:action];
    [self.sender presentViewController:alert animated:YES completion:nil];
}

#pragma mark - UICollectionDataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.maxPreviewCount>_arrayDataSources.count?_arrayDataSources.count:self.maxPreviewCount;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    SelectCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"SelectCollectionCell" forIndexPath:indexPath];
    
    cell.btnSelect.selected = NO;
    [cell.btnSelect setBackgroundImage:[UIImage imageNamed:@"btn_unselected"] forState:UIControlStateNormal];
    PHAsset *asset = _arrayDataSources[indexPath.row];
    [self getImageWithAsset:asset completion:^(UIImage *image) {
        cell.imageView.image = image;
        for (ZZPhoto *photo in _arraySelectPhotos) {
            if ([photo.asset isEqual:asset]) {
                cell.btnSelect.selected = YES;
                [cell.btnSelect setBackgroundImage:[UIImage imageNamed:@"btn_selected"] forState:UIControlStateNormal];
                break;
            }
        }
    }];
    
    cell.btnSelect.tag = indexPath.row;
    [cell.btnSelect addTarget:self action:@selector(cell_btn_Click:) forControlEvents:UIControlEventTouchUpInside];
    
    return cell;
}

- (void)cell_btn_Click:(UIButton *)btn
{
    if (_arraySelectPhotos.count >= self.maxSelectCount
        && btn.selected == NO) {
        ShowToastLong(@"最多只能选择%ld张图片", (long)self.maxSelectCount);
        return;
    }
    btn.selected = !btn.selected;
    PHAsset *asset = _arrayDataSources[btn.tag];
    SelectCollectionCell *cell = (SelectCollectionCell *)[self.collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForRow:btn.tag inSection:0]];
    if (btn.selected) {
        [btn setBackgroundImage:[UIImage imageNamed:@"btn_selected"] forState:UIControlStateNormal];
        [btn.layer addAnimation:[ZLAnimationTool animateWithBtnStatusChanged] forKey:nil];
        
        ZZPhoto *photo = [[ZZPhoto alloc]init];
        photo.asset = asset;
        
//        SelectPhotoModel *model = [[SelectPhotoModel alloc] init];
//        model.asset = asset;
//        model.image = cell.imageView.image;
//        model.imageName = [asset valueForKey:@"filename"];
        
        [_arraySelectPhotos addObject:photo];
    } else {
        [btn setBackgroundImage:[UIImage imageNamed:@"btn_unselected"] forState:UIControlStateNormal];
        for (ZZPhoto *photo in _arraySelectPhotos) {
            if ([photo.asset isEqual:asset]) {
                [_arraySelectPhotos removeObject:photo];
                break;
            }
        }
    }
    
    [self changeBtnCameraTitle];
}
#pragma MARK - 改变title文字
- (void)changeBtnCameraTitle
{
    if (_arraySelectPhotos.count >0) {
        isSure = YES;
    }else
    {
        isSure = NO;
    }
    [table reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:0 inSection:0]] withRowAnimation:UITableViewRowAnimationNone];

}


#pragma mark - UICollectionViewDelegate
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    PHAsset *asset = _arrayDataSources[indexPath.row];
    return [self getSizeWithAsset:asset];
}

- (void)hide
{
    if (_animate) {
//        CGPoint fromPoint = self.baseView.layer.position;
        CGPoint toPoint   = CGPointMake(fromPoint.x, fromPoint.y+300);
        CABasicAnimation *animation = [ZLAnimationTool animateWithFromValue:[NSValue valueWithCGPoint:fromPoint] toValue:[NSValue valueWithCGPoint:toPoint] duration:0.1 keyPath:@"position"];
        animation.delegate = self;
        
        [self.layer addAnimation:animation forKey:nil];
    } else {
        self.hidden = YES;
        [self removeFromSuperview];
    }
}

- (void)done
{
    if (self.handler) {
        NSMutableArray *selPhoto = [NSMutableArray array];
        for (ZZPhoto *photo in _arraySelectPhotos) {
            if (photo.asset == nil) {
                continue;
            }
            [self.datas GetImageObject:photo.asset complections:^(UIImage *photo, BOOL isDegraded) {
                if (isDegraded) {
                    return;
                }
                if (selPhoto){
                    [selPhoto addObject:photo];
                }
                if (selPhoto.count < _arraySelectPhotos.count){
                    return;
                }
                self.handler(selPhoto);
                
            }];
//            [self.datas GetImageObjects:photo.asset complections:^(UIImage *photo ,BOOL isDegradedResult) {
//                if (isDegradedResult) {
//                    return;
//                }
//                if (selPhoto){
//                    [selPhoto addObject:photo];
//                }
//                if (selPhoto.count < _arraySelectPhotos.count){
//                    return;
//                }
//                self.handler(selPhoto);
//
//                
//            }]
            
            
//            [selPhoto addObject:photo];
        }
        
    }
}

#pragma mark --- 懒加载
-(ZZPhotoDatas *)datas{
    if (!_datas) {
        _datas = [[ZZPhotoDatas alloc]init];
    }
    return _datas;
}

- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag
{
    self.hidden = YES;
    [self removeFromSuperview];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self hide];
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    ZLShowBigImgViewController *svc = [[ZLShowBigImgViewController alloc] init];
    svc.assets         = _arrayDataSources;
    svc.arraySelectPhotos = [NSMutableArray arrayWithArray:_arraySelectPhotos];
    svc.selectIndex    = indexPath.row;
    svc.maxSelectCount = _maxSelectCount;
    svc.showPopAnimate = YES;
    svc.shouldReverseAssets = YES;
    __weak typeof(self) weakSelf = self;
    
    [svc setOnSelectedPhotos:^(NSArray *selectedPhotos) {
        [weakSelf.arraySelectPhotos removeAllObjects];
        [weakSelf.arraySelectPhotos addObjectsFromArray:selectedPhotos];
        [weakSelf changeBtnCameraTitle];
        [weakSelf.collectionView reloadData];
    }];
    [self.sender.navigationController.view.layer addAnimation:[ZLAnimationTool animateWithType:kCATransitionMoveIn subType:kCATransitionFromTop duration:0.3] forKey:nil];
    self.sender.hidesBottomBarWhenPushed = YES;
    [self.sender.navigationController pushViewController:svc animated:NO];
}

#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    __weak typeof(PhotoActionSheetView *) weakSelf = self;
    [picker dismissViewControllerAnimated:YES completion:^{
        if (weakSelf.handler) {
            UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
            weakSelf.handler(@[image]);
            UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextinfo:), nil);
        }
        [weakSelf hide];
    }];
}

//写入相册后回调方法
- (void)image:(NSString *)video didFinishSavingWithError:(NSError *)error contextinfo:(void *)contextInfo
{
    //do something
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    __weak typeof(PhotoActionSheetView *) weakSelf = self;
    [picker dismissViewControllerAnimated:YES completion:^{
        [weakSelf hide];
    }];
}


#pragma mark - 获取图片及图片尺寸的相关方法
- (CGSize)getSizeWithAsset:(PHAsset *)asset
{
    CGFloat width  = (CGFloat)asset.pixelWidth;
    CGFloat height = (CGFloat)asset.pixelHeight;
    CGFloat scale = width/height;
    
    return CGSizeMake(self.collectionView.frame.size.height*scale, self.collectionView.frame.size.height);
}

- (void)getImageWithAsset:(PHAsset *)asset completion:(void (^)(UIImage *image))completion
{
    CGSize size = [self getSizeWithAsset:asset];
    size.width  *= 2;
    size.height *= 2;
    [[ZLPhotoTool sharePhotoTool] requestImageForAsset:asset size:size resizeMode:PHImageRequestOptionsResizeModeFast completion:completion];
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end