Last active
August 29, 2015 14:05
-
-
Save ipreencekmr/577b586916d23b2f8330 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// ImageSelector.m | |
// PG | |
// | |
// Created by Prince Kumar on 8/8/14. | |
// Copyright (c) 2014 Prince Kumar. All rights reserved. | |
// | |
#import <UIKit/UIKit.h> | |
enum AssetMediaType{ | |
kMediaTypePhoto, | |
kMediaTypeVideo, | |
kMediaTypeAll | |
}; | |
@class AVSelector; | |
@protocol AVSelectorDelegate <NSObject> | |
-(void)assetPickerController:(AVSelector*)picker didFinishPickingMediaItems:(NSArray*)items; | |
@end | |
@protocol AVSelectorDataSource <NSObject> | |
-(NSInteger)numberOfSelectionAllowsInPicker:(AVSelector*)picker; | |
@end | |
@interface AVSelector : UIViewController<UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,UICollectionViewDelegate> | |
{ | |
UICollectionView *_collectionView; | |
id <AVSelectorDelegate> avdelegate; | |
id <AVSelectorDataSource> avdatasource; | |
} | |
@property(nonatomic,assign)enum AssetMediaType mediaType; | |
@property(nonatomic,strong)id <AVSelectorDelegate> avdelegate; | |
@property(nonatomic,strong)id <AVSelectorDataSource> avdatasource; | |
@end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// ImageSelector.m | |
// PG | |
// | |
// Created by Prince Kumar on 8/8/14. | |
// Copyright (c) 2014 Prince Kumar. All rights reserved. | |
// | |
#import "AVSelector.h" | |
#import <AssetsLibrary/AssetsLibrary.h> | |
@interface AVSelector () | |
{ | |
__block NSMutableArray *thumbsArr; | |
__block NSMutableArray *urlArray; | |
__block NSMutableArray *durationArray; | |
__block NSMutableArray *assetTypeArray; | |
BOOL _done; | |
NSMutableArray *selectedIndexArr; | |
UIActivityIndicatorView *indicator; | |
} | |
@end | |
@implementation AVSelector | |
@synthesize avdatasource,avdelegate; | |
-(id)init{ | |
self = [super init]; | |
if (self) { | |
thumbsArr = [[NSMutableArray alloc] init]; | |
urlArray = [[NSMutableArray alloc] init]; | |
selectedIndexArr = [[NSMutableArray alloc] init]; | |
durationArray = [[NSMutableArray alloc] init]; | |
assetTypeArray = [[NSMutableArray alloc] init]; | |
self.mediaType = kMediaTypeAll; | |
} | |
return self; | |
} | |
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil | |
{ | |
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; | |
if (self) { | |
thumbsArr = [[NSMutableArray alloc] init]; | |
urlArray = [[NSMutableArray alloc] init]; | |
selectedIndexArr = [[NSMutableArray alloc] init]; | |
durationArray = [[NSMutableArray alloc] init]; | |
assetTypeArray = [[NSMutableArray alloc] init]; | |
self.mediaType = kMediaTypeAll; | |
// Custom initialization | |
} | |
return self; | |
} | |
-(BOOL)isIphone5 | |
{ | |
if(UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone){ | |
if ([[UIScreen mainScreen] respondsToSelector: @selector(scale)]) { | |
CGSize result = [[UIScreen mainScreen] bounds].size; | |
CGFloat scale = [UIScreen mainScreen].scale; | |
result = CGSizeMake(result.width * scale, result.height * scale); | |
if(result.height == 960){ | |
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0) { | |
return NO; | |
} | |
} | |
if(result.height == 1136){ | |
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0) { | |
return YES; | |
} | |
} | |
} | |
} | |
return NO; | |
} | |
-(void)loadAssets{ | |
__block NSDate *now = [NSDate date]; | |
__block NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; | |
dateFormatter.dateFormat = @"hh:mm:ss"; | |
[dateFormatter setTimeZone:[NSTimeZone systemTimeZone]]; | |
NSLog(@"Start: %@",[dateFormatter stringFromDate:now]); | |
__block ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init]; | |
[library enumerateGroupsWithTypes:ALAssetsGroupAll usingBlock:^(ALAssetsGroup *group, BOOL *stop) { | |
if (self.mediaType == kMediaTypeVideo) { | |
[group setAssetsFilter:[ALAssetsFilter allVideos]]; | |
} | |
if(self.mediaType == kMediaTypePhoto){ | |
[group setAssetsFilter:[ALAssetsFilter allPhotos]]; | |
} | |
[group enumerateAssetsWithOptions:NSEnumerationReverse usingBlock:^(ALAsset *alAsset, NSUInteger index, BOOL *innerStop) { | |
if (alAsset) { | |
ALAssetRepresentation *representation = [alAsset defaultRepresentation]; | |
UIImage *latestPhotoThumbnail = [UIImage imageWithCGImage:[alAsset thumbnail]]; | |
[urlArray addObject:representation.url]; | |
[thumbsArr addObject:latestPhotoThumbnail]; | |
enum AssetMediaType assetType = kMediaTypeAll; | |
if ([[alAsset valueForProperty:ALAssetPropertyType] isEqualToString:ALAssetTypeVideo]) { | |
NSNumber *duration = [alAsset valueForProperty:ALAssetPropertyDuration]; | |
if ([alAsset valueForProperty:ALAssetPropertyDuration] != ALErrorInvalidProperty) { | |
NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; | |
[formatter setDateFormat:@"mm:ss"]; | |
NSTimeInterval timeSince1970 = [duration doubleValue]; | |
NSDate *date = [NSDate dateWithTimeIntervalSince1970:timeSince1970]; | |
date = [date dateByAddingTimeInterval:-30*60]; | |
[durationArray addObject:[formatter stringFromDate:date]]; | |
formatter = nil; | |
date = nil; | |
}else{ | |
[durationArray addObject:@"NA"]; | |
} | |
assetType = kMediaTypeVideo; | |
[assetTypeArray addObject:[NSNumber numberWithInt:assetType]]; | |
duration = nil; | |
} | |
if ([[alAsset valueForProperty:ALAssetPropertyType] isEqualToString:ALAssetTypePhoto]) { | |
[durationArray addObject:@"NA"]; | |
assetType = kMediaTypePhoto; | |
[assetTypeArray addObject:[NSNumber numberWithInt:assetType]]; | |
} | |
representation = nil; | |
latestPhotoThumbnail = nil; | |
}else{ | |
now = [NSDate date]; | |
NSLog(@"End: %@",[dateFormatter stringFromDate:now]); | |
now = nil; | |
library = nil; | |
dateFormatter = nil; | |
NSLog(@"Asset Type %lu",(unsigned long)[assetTypeArray count]); | |
NSLog(@"dur %lu,%@",(unsigned long)[durationArray count],durationArray); | |
NSLog(@"url arr %lu",(unsigned long)[urlArray count]); | |
NSLog(@"thumbs arr %lu",(unsigned long)[thumbsArr count]); | |
[indicator stopAnimating]; | |
[indicator removeFromSuperview]; | |
[_collectionView reloadData]; | |
} | |
}]; | |
} failureBlock: ^(NSError *error) { | |
NSLog(@"No groups: %@",error); | |
}]; | |
} | |
- (void)viewDidLoad | |
{ | |
_done = NO; | |
indicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge]; | |
indicator.backgroundColor = [UIColor blackColor]; | |
indicator.layer.cornerRadius = 4.0; | |
indicator.alpha = 0.8; | |
indicator.frame = CGRectMake(0, 0, 45, 45); | |
indicator.center = self.view.center; | |
self.view = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; | |
CGRect controllerFrame = self.view.frame; | |
controllerFrame.origin.y = 64; | |
controllerFrame.size.height-=64; | |
UIToolbar *controllerBar = [[UIToolbar alloc] initWithFrame:CGRectMake(0,20, controllerFrame.size.width, 44)]; | |
controllerBar.tintColor = [UIColor colorWithRed:255.0/255.0 green:102.0/255.0 blue:51.0/255.0 alpha:0.9]; | |
controllerBar.barStyle = UIBarStyleBlack; | |
UIBarButtonItem *cancel = [[UIBarButtonItem alloc] initWithTitle:@"Cancel" style:UIBarButtonItemStyleBordered target:self action:@selector(cancel)]; | |
UIBarButtonItem *flexibleItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil]; | |
UIBarButtonItem *done = [[UIBarButtonItem alloc] initWithTitle:@"Done" style:UIBarButtonItemStyleDone target:self action:@selector(done)]; | |
[cancel setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys: [UIColor whiteColor], NSForegroundColorAttributeName,nil] forState:UIControlStateNormal]; | |
[done setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys: [UIColor whiteColor], NSForegroundColorAttributeName,nil] forState:UIControlStateNormal]; | |
[controllerBar setItems:@[cancel,flexibleItem,done] animated:YES]; | |
UICollectionViewFlowLayout *layout=[[UICollectionViewFlowLayout alloc] init]; | |
_collectionView=[[UICollectionView alloc] initWithFrame:controllerFrame collectionViewLayout:layout]; | |
_collectionView.allowsMultipleSelection = YES; | |
[_collectionView setDataSource:self]; | |
[_collectionView setDelegate:self]; | |
[_collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"im_cell_identifier"]; | |
[_collectionView setBackgroundColor:[UIColor whiteColor]]; | |
[self.view addSubview:controllerBar]; | |
[self.view addSubview:_collectionView]; | |
[super viewDidLoad]; | |
// Do any additional setup after loading the view. | |
} | |
-(void)viewDidAppear:(BOOL)animated | |
{ | |
[self loadAssets]; | |
} | |
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section | |
{ | |
return [thumbsArr count]; | |
} | |
// The cell that is returned must be retrieved from a call to -dequeueReusableCellWithReuseIdentifier:forIndexPath: | |
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath | |
{ | |
UICollectionViewCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:@"im_cell_identifier" forIndexPath:indexPath]; | |
UIImageView *imgView = (UIImageView*)[cell viewWithTag:21]; | |
UIImageView *checked = (UIImageView*)[cell viewWithTag:44]; | |
UIImageView *vdoImg = (UIImageView*)[cell viewWithTag:99]; | |
UILabel *durLabel = (UILabel*)[cell viewWithTag:33]; | |
if (imgView==nil) { | |
imgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 75, 75)]; | |
imgView.tag =21; | |
imgView.center = CGPointMake(cell.frame.size.width/2, cell.frame.size.height/2); | |
cell.backgroundColor = [UIColor whiteColor]; | |
[cell addSubview:imgView]; | |
} | |
if (checked==nil) { | |
checked = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 20, 20)]; | |
checked.tag = 44; | |
checked.center = CGPointMake(cell.frame.size.width/2, cell.frame.size.height/2); | |
[cell addSubview:checked]; | |
} | |
if (durLabel==nil) { | |
durLabel = [[ UILabel alloc] initWithFrame:CGRectMake(0, cell.frame.size.height-19,cell.frame.size.width,20)]; | |
durLabel.tag = 33; | |
[durLabel setTextAlignment:NSTextAlignmentRight]; | |
[durLabel setTextColor:[UIColor whiteColor]]; | |
[durLabel setFont:[UIFont boldSystemFontOfSize:12.0f]]; | |
[cell addSubview:durLabel]; | |
} | |
if (vdoImg==nil) { | |
vdoImg = [[UIImageView alloc] initWithFrame:CGRectMake(5,cell.frame.size.height-15,15,12)]; | |
vdoImg.tag = 99; | |
[cell addSubview:vdoImg]; | |
} | |
if (cell.selected) { | |
[checked setImage:[UIImage imageNamed:@"check.png"]]; | |
[cell setBackgroundColor:[UIColor orangeColor]]; | |
}else{ | |
[checked setImage:nil]; | |
[cell setBackgroundColor:[UIColor whiteColor]]; | |
[imgView setAlpha:1.0f]; | |
} | |
enum AssetMediaType mediaType = [[assetTypeArray objectAtIndex:indexPath.row] intValue]; | |
if (mediaType==kMediaTypeVideo) { | |
[vdoImg setImage:[UIImage imageNamed:@"vdo.png"]]; | |
[durLabel setBackgroundColor:[UIColor clearColor]]; | |
durLabel.alpha = 0.8; | |
}else{ | |
[vdoImg setImage:nil]; | |
[durLabel setBackgroundColor:[UIColor clearColor]]; | |
} | |
if ([durationArray[indexPath.row] isEqualToString:@"NA"]) { | |
[durLabel setText:@" "]; | |
}else{ | |
NSString *pad = [[NSString string] stringByPaddingToLength:1 withString:@"`" startingAtIndex:0]; | |
[durLabel setText:[[durationArray objectAtIndex:indexPath.row] stringByAppendingString:pad]]; | |
pad = nil; | |
} | |
[imgView setImage:[thumbsArr objectAtIndex:indexPath.row]]; | |
return cell; | |
} | |
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath | |
{ | |
return CGSizeMake(75, 75); | |
} | |
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section | |
{ | |
return 5; | |
} | |
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section | |
{ | |
return 2.5; | |
} | |
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section | |
{ | |
return UIEdgeInsetsMake(5, 5, 10, 5); | |
} | |
#pragma mark - Collection view delegate | |
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath | |
{ | |
if ([self.avdatasource respondsToSelector:@selector(numberOfSelectionAllowsInPicker:)]) { | |
NSInteger limit = [self.avdatasource numberOfSelectionAllowsInPicker:self]; | |
if ([selectedIndexArr count]>=limit) { | |
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"No more selection allowed." delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil]; | |
[alert show]; | |
return; | |
} | |
} | |
UICollectionViewCell *cell = [collectionView cellForItemAtIndexPath:indexPath]; | |
cell.backgroundColor = [UIColor orangeColor]; | |
UIImageView *checked = (UIImageView*)[cell viewWithTag:44]; | |
[checked setImage:[UIImage imageNamed:@"check.png"]]; | |
UIImageView *imgView = (UIImageView*)[cell viewWithTag:21]; | |
[imgView setAlpha:0.7f]; | |
NSURL *url = [urlArray objectAtIndex:indexPath.row]; | |
[selectedIndexArr addObject:url]; | |
url = nil; | |
checked = nil; | |
cell = nil; | |
imgView = nil; | |
} | |
- (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath | |
{ | |
UICollectionViewCell *cell = [collectionView cellForItemAtIndexPath:indexPath]; | |
cell.backgroundColor = [UIColor whiteColor]; | |
UIImageView *checked = (UIImageView*)[cell viewWithTag:44]; | |
[checked setImage:nil]; | |
UIImageView *imgView = (UIImageView*)[cell viewWithTag:21]; | |
[imgView setAlpha:1.0f]; | |
NSURL *url = [urlArray objectAtIndex:indexPath.row]; | |
[selectedIndexArr removeObject:url]; | |
cell = nil; | |
checked = nil; | |
url = nil; | |
imgView = nil; | |
} | |
#pragma mark - BarButton Methods | |
-(void)cancel | |
{ | |
[self dismissViewControllerAnimated:YES completion:nil]; | |
} | |
-(void)done | |
{ | |
if (_done==NO) { | |
_done = YES; | |
[self.view addSubview:indicator]; | |
[indicator startAnimating]; | |
__block NSMutableArray *assetArray = [[NSMutableArray alloc] initWithCapacity:[selectedIndexArr count]]; | |
[selectedIndexArr enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { | |
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init]; | |
[library assetForURL:obj resultBlock:^(ALAsset *asset) { | |
ALAssetRepresentation *representation = [asset defaultRepresentation]; | |
if ([[asset valueForProperty:@"ALAssetPropertyType"] isEqualToString:@"ALAssetTypePhoto"]) { | |
UIImage *latestPhoto = [UIImage imageWithCGImage:[representation fullScreenImage]]; | |
NSData *imgData = UIImagePNGRepresentation(latestPhoto); | |
NSString *imageName = [NSString stringWithFormat:@"s_img_%f.png",[[NSDate date] timeIntervalSince1970]]; | |
[imgData writeToFile:[NSTemporaryDirectory() stringByAppendingPathComponent:imageName] atomically:YES]; | |
[assetArray addObject:[NSURL fileURLWithPath:[NSTemporaryDirectory() stringByAppendingPathComponent:imageName]]]; | |
latestPhoto = nil; | |
imgData = nil; | |
imageName = nil; | |
}else{ | |
NSString *vdoName = [NSString stringWithFormat:@"s_vdo_%f.mov",[[NSDate date] timeIntervalSince1970]]; | |
Byte *buffer = (Byte*)malloc(representation.size); | |
NSUInteger buffered = [representation getBytes:buffer fromOffset:0.0 length:representation.size error:nil]; | |
NSData *vdoData = [NSData dataWithBytesNoCopy:buffer length:buffered freeWhenDone:YES]; | |
BOOL success = [vdoData writeToFile:[NSTemporaryDirectory() stringByAppendingPathComponent:vdoName] atomically:YES]; | |
if (success) { | |
[assetArray addObject:[NSURL fileURLWithPath:[NSTemporaryDirectory() stringByAppendingPathComponent:vdoName]]]; | |
} | |
vdoName = nil; | |
buffer = nil; | |
vdoData = nil; | |
} | |
if ([assetArray count]==[selectedIndexArr count]) { | |
if ([self.avdelegate respondsToSelector:@selector(assetPickerController:didFinishPickingMediaItems:)]) { | |
[self.avdelegate assetPickerController:self didFinishPickingMediaItems:assetArray]; | |
} | |
assetArray = nil; | |
} | |
} failureBlock:^(NSError *error) { | |
NSLog(@"Failure picking media"); | |
}]; | |
}]; | |
} | |
} | |
- (UIStatusBarStyle) preferredStatusBarStyle { | |
if ([self isIphone5]) { | |
return UIStatusBarStyleLightContent; | |
} | |
return UIStatusBarStyleDefault; | |
} | |
-(void)viewDidDisappear:(BOOL)animated{ | |
thumbsArr = nil; | |
urlArray = nil; | |
selectedIndexArr = nil; | |
durationArray = nil; | |
assetTypeArray = nil; | |
_collectionView = nil; | |
indicator = nil; | |
} | |
- (void)didReceiveMemoryWarning | |
{ | |
[super didReceiveMemoryWarning]; | |
// Dispose of any resources that can be recreated. | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment