ALAssetsGroupEnumerationResultsBlock assetsEnumerationBlock = ^(ALAsset *result, NSUInteger index, BOOL *stop)
{
if (result) {
[assets addObject:result];
ALAssetRepresentation *rep = [result defaultRepresentation];
photoname=[rep filename];
imageurl=[rep url];
NSLog(#"result %#",result);
NSLog(#"name %#",photoname);//Img0001.Jpg
NSLog(#"name %#",imageurl);//assets-library://asset/asset.JPG?id=3B36DBC8-A2F7-4088-ADEF-A9E2FF8FD927&ext=JPG
[print addObject:photoname];
//NsuserDefaults
// NSMutableArray *mutableArray = [[NSMutableArray alloc] initWithArray:print];
// [[NSUserDefaults standardUserDefaults] setObject:mutableArray forKey:#"test"];
retArray = [[NSMutableArray alloc] initWithArray:((NSMutableArray *) [[NSUserDefaults standardUserDefaults] objectForKey:#"test"])];
NSLog(#"res %#",retArray);
}
};
ALAssetsFilter *onlyPhotosFilter = [ALAssetsFilter allPhotos];
[self.assetsGroup setAssetsFilter:onlyPhotosFilter];
[self.assetsGroup enumerateAssetsUsingBlock:assetsEnumerationBlock];
}
You need to use the assets library to get the asset for the URL, and then get the image from the asset. Currently you are treating the asset URL as an asset rather than using the URL to get the asset:
[self.assetsLibrary assetForURL:assetURL resultBlock:^(ALAsset * asset) {
UIImage *image = [UIImage imageWithCGImage:[asset thumbnail]];
// use the image for something
}
NSURL *assetURL = notequal[indexPath.row];
[self.assetslibrary assetForURL:assetURL resultBlock:^(ALAsset * asset) {
UIImage *image = [UIImageimageWithCGImage[asset thumbnail]];
UIImageView *imageView = (UIImageView *)[cell viewWithTag:kImageViewTag];
imageView.image = thumbnail;
}];
return cell;
Related
I want to display the thumbnail of videos by using ALAssetLibrary and for displaying the video from gallery to my app , i filtered all videos from ALAssetsFilter .
But still i am getting the null value in asset of type ALAsset.
Please tell me what i am doing wrong with my code.
Appreciate for the help.
-(void)loadAssets{
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
[library enumerateGroupsWithTypes:ALAssetsGroupAll usingBlock:^(ALAssetsGroup *group, BOOL *stop) {
[group setAssetsFilter:[ALAssetsFilter allVideos]];
[group enumerateAssetsWithOptions:NSEnumerationReverse usingBlock:^(ALAsset *asset, NSUInteger index, BOOL *innerStop) {
if (asset)
{
dic = [[NSMutableDictionary alloc] init];
ALAssetRepresentation *defaultRepresentation = [asset defaultRepresentation];
NSString *uti = [defaultRepresentation UTI];
videoURL = [[asset valueForProperty:ALAssetPropertyURLs] valueForKey:uti];
NSString *title = [NSString stringWithFormat:#"video %d", arc4random()%100];
UIImage *image = [self imageFromVideoURL:videoURL];
[dic setValue:image forKey:#"image"];
[dic setValue:title forKey:#"name"];
[dic setValue:videoURL forKey:#"url"];
[allVideos addObject:asset];
}
}];
[_collectionView reloadData];
}
failureBlock:^(NSError *error)
{
NSLog(#"error enumerating AssetLibrary groups %#\n", error);
}];
}
- (UIImage *)imageFromVideoURL:(NSURL*)videoURL
{
UIImage *image = nil;
AVAsset *asset = [[AVURLAsset alloc] initWithURL:videoURL options:nil];;
AVAssetImageGenerator *imageGenerator = [[AVAssetImageGenerator alloc] initWithAsset:asset];
imageGenerator.appliesPreferredTrackTransform = YES;
// calc midpoint time of video
Float64 durationSeconds = CMTimeGetSeconds([asset duration]);
CMTime midpoint = CMTimeMakeWithSeconds(durationSeconds/2.0, 600);
// get the image from
NSError *error = nil;
CMTime actualTime;
CGImageRef halfWayImage = [imageGenerator copyCGImageAtTime:midpoint actualTime:&actualTime error:&error];
if (halfWayImage != NULL)
{
// cgimage to uiimage
image = [[UIImage alloc] initWithCGImage:halfWayImage];
[dic setValue:image forKey:#"ImageThumbnail"];//kImage
NSLog(#"Values of dictonary==>%#", dic);
NSLog(#"Videos Are:%#",allVideos);
CGImageRelease(halfWayImage);
}
return image;
}
Use this code may this will help you to generate thumbnail image-- -
-(UIImage*)loadImage {
AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:self.videoURL options:nil];
AVAssetImageGenerator *generate = [[AVAssetImageGenerator alloc] initWithAsset:asset];
generate.appliesPreferredTrackTransform = YES;
NSError *err = NULL;
CMTime time = CMTimeMake(1, 60);
CGImageRef imgRef = [generate copyCGImageAtTime:time actualTime:NULL error:&err];
return [[UIImage alloc] initWithCGImage:imgRef];
}
I have Create the Thumbnail image from Video, its working for me and the code is below,
NSURL *videoURL = [info objectForKey:UIImagePickerControllerMediaURL];
NSLog(#"store url %#",videoURL);
AVAsset *avAsset = [AVURLAsset URLAssetWithURL:videoURL options:nil];
if ([[avAsset tracksWithMediaType:AVMediaTypeVideo] count] > 0)
{
AVAssetImageGenerator *imageGenerator =[AVAssetImageGenerator assetImageGeneratorWithAsset:avAsset];
Float64 durationSeconds = CMTimeGetSeconds([avAsset duration]);
CMTime midpoint = CMTimeMakeWithSeconds(durationSeconds/2.0, 600);
NSError *error;
CMTime actualTime;
CGImageRef halfWayImage = [imageGenerator copyCGImageAtTime:kCMTimeZero actualTime:&actualTime error:&error];
if (halfWayImage != NULL)
{
NSString *actualTimeString = (NSString *)CFBridgingRelease(CMTimeCopyDescription(NULL, actualTime));
NSString *requestedTimeString = (NSString *)CFBridgingRelease(CMTimeCopyDescription(NULL, midpoint));
NSLog(#"Got halfWayImage: Asked for %#, got %#", requestedTimeString, actualTimeString);
UIImage *img=[UIImage imageWithCGImage:halfWayImage];
playButton.hidden=NO;
self.myimageView.image= img; //[self scaleImage:img maxWidth:(img.size.width/5) maxHeight:(img.size.height/5)];
}
}
Finally got the thumbnail image, hope its helpful
I want to create a custom library where i will get all videos with their folder name. I implemented some code but this is not working properly. My code get videos from some folders but also drop some folder. i want to fetch all folders.
This is my code:-
-(void)getAllVideos
{
assetItems = [NSMutableArray arrayWithCapacity:0];
allVideos = [[NSMutableArray alloc] init];
ALAssetsLibrary *assetLibrary = [[ALAssetsLibrary alloc] init];
[assetLibrary enumerateGroupsWithTypes:ALAssetsGroupAll usingBlock:^(ALAssetsGroup *group, BOOL *stop)
{
if (group)
{
NSString * str = [NSString stringWithFormat:#"%#",group];
int power = [str rangeOfString:#","].location;
NSString *str1= [str substringToIndex:power];
int dash = [str rangeOfString:#":"].location;
NSString *final = [str1 substringFromIndex:dash+1];
combineArray =[[NSMutableArray alloc]init];
thumbnailImages = [[NSMutableArray alloc]init];
videosURL = [[NSMutableArray alloc]init];
NSLog(#"name of folder%#",group);
[groupName addObject:final];
[group setAssetsFilter:[ALAssetsFilter allVideos]];
[group enumerateAssetsUsingBlock:^(ALAsset *asset, NSUInteger index, BOOL *stop)
{
if (asset)
{
dic = [[NSMutableDictionary alloc] init];
ALAssetRepresentation *defaultRepresentation = [asset defaultRepresentation];
NSString *uti = [defaultRepresentation UTI];
NSURL *videoURL = [[asset valueForProperty:ALAssetPropertyURLs] valueForKey:uti];
NSString *title = [NSString stringWithFormat:#"video %d", arc4random()%100];
AVAsset *asset = [AVAsset assetWithURL:videoURL];
AVAssetImageGenerator *imageGenerator = [[AVAssetImageGenerator alloc]initWithAsset:asset];
CMTime time = [asset duration];
time.value = 0;
CGImageRef imageRef = [imageGenerator copyCGImageAtTime:time actualTime:NULL error:NULL];
UIImage *thumbnail = [UIImage imageWithCGImage:imageRef];
CGImageRelease(imageRef);
[thumbnailImages addObject:thumbnail];
[videosURL addObject:videoURL];
}
} ];
if(thumbnailImages.count >0)
[combineArray addObject:thumbnailImages];
if(videosURL.count > 0)
[combineArray addObject:videosURL];
if(combineArray.count>0)
[alldata setObject:combineArray forKey:final];
}
// group == nil signals we are done iterating.
else
{
dispatch_async(dispatch_get_main_queue(), ^{
});
}
}
failureBlock:^(NSError *error)
{
NSLog(#"error enumerating AssetLibrary groups %#\n", error);
}];
}
Please suggest me what changes i have to do?
I have ViewController1 and ViewController2.
ViewController1 is UICollectionView and it use ASAssetLibrary to load thumbnail into UICollectionViewCell:
NSMutableArray *collector = [[NSMutableArray alloc] initWithCapacity:0];
ALAssetsLibrary *al = [TemplateEditBarController defaultAssetsLibrary];
[al enumerateGroupsWithTypes:ALAssetsGroupSavedPhotos
usingBlock:^(ALAssetsGroup *group, BOOL *stop)
{
[group enumerateAssetsUsingBlock:^(ALAsset *asset, NSUInteger index, BOOL *stop)
{
if (asset) {
[collector addObject:asset];
}
}];
assetsarray = collector;//<--assetsarray is local.
}
failureBlock:^(NSError *error) { NSLog(#"fail!");}
];
When cell selected, I want to pass either NSString or NSURL to ViewController2 so that it will call and display the full resolution image. But when NSLog the url:
ALAsset* asset = backgroundsarray[row];
ALAssetRepresentation *representation = [asset defaultRepresentation];
NSURL *url = [representation url];
newbg = [url absoluteString];//<-NSLog this.
I get:
assets-library://asset/asset.JPG?id=6E5438ED-9A8C-4ED0-9DEA-AB2D8F8A9360&ext=JPG
I tried change to [url path] I get:
asset.JPG
How can I get the actual photo url so that I can convert to NSString to pass to ViewController2?
NSURL* aURL = [NSURL URLWithString:imagePath];
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
[library assetForURL:aURL resultBlock:^(ALAsset *asset)
{
UIImage *image = [UIImage imageWithCGImage:[[asset defaultRepresentation] fullScreenImage] scale:0.5 orientation:UIImageOrientationUp];
imageView.image=image;
}
failureBlock:^(NSError *error)
{
// error handling
NSLog(#"failure-----");
}];
My solution here:
ALAssetsLibrary *assetslibrary = [[ALAssetsLibrary alloc] init];
[assetslibrary assetForURL:assetURL resultBlock:^(ALAsset *asset) {
if (asset) {
image = [UIImage imageWithCGImage:[asset aspectRatioThumbnail]];
}
}
Apparently there isn't any direct solution other than passing ALAsset. This is what I do:
In ViewController1, which is UICollectionViewController, I have this function:
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
//NSLog(#"selected row: %ld",(long)indexPath.row);
long row = [indexPath row];
NSString* newbg = [[NSString alloc]init];
if ([bartype isEqualToString:#"photolibrary"]) {
ALAsset* asset = backgroundsarray[row];
[_delegate changeBackgroundWithAsset:asset];
}
Then I have a function in ViewController2 to process ALAsset:
-(void)changeBackgroundWithAsset:(ALAsset*)b{
ALAssetRepresentation *rep = [b defaultRepresentation];
CGImageRef iref = [rep fullResolutionImage];
UIImage *bimage;
bimage = [UIImage imageWithCGImage:iref];
UIImageView* bgview = [[UIImageView alloc]init];
bgview = curbgview;
bgview.image = bimage;
}
- (void)showVideoList
{
[self buildAssetsLibrary];
}
- (void)buildAssetsLibrary
{
assetsLibrary = [[ALAssetsLibrary alloc] init];
ALAssetsLibrary *notificationSender = nil;
videoURLArray = [[NSMutableArray alloc] init];
NSString *minimumSystemVersion = #"4.1";
NSString *systemVersion = [[UIDevice currentDevice] systemVersion];
if ([systemVersion compare:minimumSystemVersion options:NSNumericSearch] != NSOrderedAscending)
notificationSender = assetsLibrary;
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(assetsLibraryDidChange:) name:ALAssetsLibraryChangedNotification object:notificationSender];
[self updateAssetsLibrary];
}
- (void)assetsLibraryDidChange:(NSNotification*)changeNotification
{
[self updateAssetsLibrary];
}
- (void)updateAssetsLibrary
{
assetItems = [NSMutableArray arrayWithCapacity:0];
ALAssetsLibrary *assetLibrary = [[ALAssetsLibrary alloc] init];
[assetLibrary enumerateGroupsWithTypes:ALAssetsGroupAll usingBlock:^(ALAssetsGroup *group, BOOL *stop)
{
if (group)
{
[group setAssetsFilter:[ALAssetsFilter allVideos]];
[group enumerateAssetsUsingBlock:^(ALAsset *asset, NSUInteger index, BOOL *stop)
{
if (asset)
{
dic = [[NSMutableDictionary alloc] init];
ALAssetRepresentation *defaultRepresentation = [asset defaultRepresentation];
NSString *uti = [defaultRepresentation UTI];
videoURL = [[asset valueForProperty:ALAssetPropertyURLs] valueForKey:uti];
mpVideoPlayer = [[MPMoviePlayerController alloc] initWithContentURL:videoURL];
NSString *title = [NSString stringWithFormat:#"%# %lu", NSLocalizedString(#"Video", nil), [assetItems count]+1];
[self performSelector:#selector(imageFromVideoURL)];
[dic setValue:title forKey:#"VideoTitle"];//kName
[dic setValue:videoURL forKey:#"VideoUrl"];//kURL
AssetBrowserItem *item = [[AssetBrowserItem alloc] initWithURL:videoURL title:title];
[assetItems addObject:item];
[videoURLArray addObject:dic];
NSLog(#"Video has info:%#",videoURLArray);
}
NSLog(#"Values of dictonary==>%#", dic);
//NSLog(#"assetItems:%#",assetItems);
NSLog(#"Videos Are:%#",videoURLArray);
} ];
}
// group == nil signals we are done iterating.
else
{
dispatch_async(dispatch_get_main_queue(), ^{
// [self updateBrowserItemsAndSignalDelegate:assetItems];
// loadImgView.hidden = NO;
// [spinner stopAnimating];
// [loadImgView removeFromSuperview];
// selectVideoBtn .userInteractionEnabled = YES;
});
}
}
failureBlock:^(NSError *error)
{
NSLog(#"error enumerating AssetLibrary groups %#\n", error);
}];
}
- (UIImage *)imageFromVideoURL
{
UIImage *image = nil;
AVAsset *asset = [[AVURLAsset alloc] initWithURL:videoURL options:nil];;
AVAssetImageGenerator *imageGenerator = [[AVAssetImageGenerator alloc] initWithAsset:asset];
imageGenerator.appliesPreferredTrackTransform = YES;
// calc midpoint time of video
Float64 durationSeconds = CMTimeGetSeconds([asset duration]);
CMTime midpoint = CMTimeMakeWithSeconds(durationSeconds/2.0, 600);
// get the image from
NSError *error = nil;
CMTime actualTime;
CGImageRef halfWayImage = [imageGenerator copyCGImageAtTime:midpoint actualTime:&actualTime error:&error];
if (halfWayImage != NULL)
{
// cgimage to uiimage
image = [[UIImage alloc] initWithCGImage:halfWayImage];
[dic setValue:image forKey:#"ImageThumbnail"];//kImage
NSLog(#"Values of dictonary==>%#", dic);
NSLog(#"Videos Are:%#",videoURLArray);
CGImageRelease(halfWayImage);
}
return image;
}
-(void)mediaPicker:(MPMediaPickerController *)mediaPicker didPickMediaItems:(MPMediaItemCollection *)mediaItemCollection
{
MPMediaItem *item = [[mediaItemCollection items] objectAtIndex:0];
NSURL *url = [item valueForProperty:MPMediaItemPropertyAssetURL];
[mediaPicker dismissViewControllerAnimated:YES completion:nil];
AVPlayerItem *playerItem=[AVPlayerItem playerItemWithURL:url];
AVPlayer *player=[[AVPlayer alloc] initWithPlayerItem:playerItem];
AVPlayerLayer *playerLayer=[AVPlayerLayer playerLayerWithPlayer:player];
playerLayer.frame=CGRectMake(0, 0, 10, 10);
[player play];
[self.view.layer addSublayer:playerLayer];
}
So I am using this code, but it asks for permission from photos. How can I get permission without the popup window?
I am trying to get list of videos from iPhone or iPad, but am unable to do so. Please help me.
Thanks in advance
Why not use the ALAssetsLibrary ? That is the recommended way of getting photos/videos out of iPhone\iPad.
I tried below code to get all videos from photo library by using ALAsset. For now, i want to display all videos to a UICollectionview but it doesn't seem to display anything. Please give me some advice. Thanks in advance.
-ViewDidLoad() : get all videos from Photo Library
allVideos = [[NSMutableArray alloc] init];
ALAssetsLibrary *assetLibrary = [[ALAssetsLibrary alloc] init];
[assetLibrary enumerateGroupsWithTypes:ALAssetsGroupAll usingBlock:^(ALAssetsGroup *group, BOOL *stop)
{
if (group)
{
[group setAssetsFilter:[ALAssetsFilter allVideos]];
[group enumerateAssetsUsingBlock:^(ALAsset *asset, NSUInteger index, BOOL *stop)
{
if (asset)
{
dic = [[NSMutableDictionary alloc] init];
ALAssetRepresentation *defaultRepresentation = [asset defaultRepresentation];
NSString *uti = [defaultRepresentation UTI];
NSURL *videoURL = [[asset valueForProperty:ALAssetPropertyURLs] valueForKey:uti];
NSString *title = [NSString stringWithFormat:#"video %d", arc4random()%100];
UIImage *image = [self imageFromVideoURL:videoURL];
[dic setValue:image forKey:#"image"];
[dic setValue:title forKey:#"name"];
[dic setValue:videoURL forKey:#"url"];
[allVideos addObject:dic];
[_collectionView reloadData];
}
}];
}
}
failureBlock:^(NSError *error)
{
NSLog(#"error enumerating AssetLibrary groups %#\n", error);
}];
-imageFromVideoURL():
- (UIImage *)imageFromVideoURL:(NSURL*)videoURL
{
// result
UIImage *image = nil;
// AVAssetImageGenerator
AVAsset *asset = [[AVURLAsset alloc] initWithURL:videoURL options:nil];;
AVAssetImageGenerator *imageGenerator = [[AVAssetImageGenerator alloc] initWithAsset:asset];
imageGenerator.appliesPreferredTrackTransform = YES;
// calc midpoint time of video
Float64 durationSeconds = CMTimeGetSeconds([asset duration]);
CMTime midpoint = CMTimeMakeWithSeconds(durationSeconds/2.0, 600);
// get the image from
NSError *error = nil;
CMTime actualTime;
CGImageRef halfWayImage = [imageGenerator copyCGImageAtTime:midpoint actualTime:&actualTime error:&error];
if (halfWayImage != NULL)
{
// CGImage to UIImage
image = [[UIImage alloc] initWithCGImage:halfWayImage];
[dic setValue:image forKey:#"name"];
NSLog(#"Values of dictionary==>%#", dic);
NSLog(#"Videos Are:%#",videoURL);
CGImageRelease(halfWayImage);
}
return image;
}
Start to display all thumbnails of video to UICollectionView:
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
return allVideos.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
UICollectionViewCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:#"cellIdentifier" forIndexPath:indexPath];
NSLog(#"allvideo %#", allVideos);
ALAsset *alasset = [allVideos objectAtIndex:indexPath.row];
return cell;
}
Replace this Line:-
[allVideos addObject:dic];
With
[allVideos addObject: asset];
And in this method:-
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
UICollectionViewCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:#"cellIdentifier" forIndexPath:indexPath];
NSLog(#"allvideo %#", allVideos);
ALAsset *alasset = [allVideos objectAtIndex:indexPath.row];
yourImageView.image = [UIImage imageWithCGImage:alasset.thumbnail];
}
First of all take the code [_collectionView reloadData] out of the ALAssetsGroupEnumerationResultsBlock (the block you passed to -enumerateAssetsUsingBlock:) as it'll call the -reloadData for all the AVAssets found.
There is a sample app "MyImagePicker" available from apple which does the exact thing you want to do. You can study the working from there.