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.
Related
I have the following code to attempt to get a screenshot of a video file from NSData. I can confirm the NSData is valid and not nil, however both dataString and movieURL are returning nil.
- (UIImage *)imageFromMovie:(NSData *)movieData {
// set up the movie player
NSString *dataString = [[NSString alloc] initWithData:movieData encoding:NSUTF8StringEncoding];
NSURL *movieURL = [NSURL URLWithString:dataString];
// get the thumbnail
AVURLAsset *asset1 = [[AVURLAsset alloc] initWithURL:movieURL options:nil];
AVAssetImageGenerator *generate1 = [[AVAssetImageGenerator alloc] initWithAsset:asset1];
generate1.appliesPreferredTrackTransform = YES;
NSError *err = NULL;
CMTime time = CMTimeMake(1, 2);
CGImageRef oneRef = [generate1 copyCGImageAtTime:time actualTime:NULL error:&err];
UIImage *one = [[UIImage alloc] initWithCGImage:oneRef];
return(one);
}
EDIT: Here's a look at where/how I'm getting the NSData from the UIImagePicker
if ([mediaType isEqualToString:#"ALAssetTypeVideo"]) {
ALAssetsLibrary *assetLibrary=[[ALAssetsLibrary alloc] init];
[assetLibrary assetForURL:[[info objectAtIndex:x] valueForKey:UIImagePickerControllerReferenceURL] resultBlock:^(ALAsset *asset) {
ALAssetRepresentation *rep = [asset defaultRepresentation];
unsigned long DataSize = (unsigned long)[rep size];
Byte *buffer = (Byte*)malloc(DataSize);
NSUInteger buffered = [rep getBytes:buffer fromOffset:0.0 length:DataSize error:nil];
//here’s the NSData
NSData *data = [NSData dataWithBytesNoCopy:buffer length:buffered freeWhenDone:YES];
} failureBlock:^(NSError *err) {
NSLog(#"Error: %#",[err localizedDescription]);
}];
}
Possible, you have problems with encoding.
NSString instance method -(id)initWithData:data:encoding returns nil if data does not represent valid data for encoding.(https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/#//apple_ref/occ/instm/NSString/initWithData:encoding:)
Try to use correct encoding in -(id)initWithData:data:encoding method.
You are trying to convert the movie data to NSURL, that's why you are getting a nil url.
In your implementation, you can get the thumbnail in the following way:
AVURLAsset *asset1 = [[AVURLAsset alloc] initWithURL:[[info objectAtIndex:x] valueForKey:UIImagePickerControllerReferenceURL] options:nil];
AVAssetImageGenerator *generate1 = [[AVAssetImageGenerator alloc] initWithAsset:asset1];
generate1.appliesPreferredTrackTransform = YES;
NSError *err = NULL;
CMTime time = CMTimeMake(1, 2);
CGImageRef oneRef = [generate1 copyCGImageAtTime:time actualTime:NULL error:&err];
UIImage *one = [[UIImage alloc] initWithCGImage:oneRef];
Download my sample project before reading this answer from:
https://drive.google.com/open?id=0B_exgT43OZJOWl9HMDJCR0cyTW8
I know it's been a really long time since you posted this question; but, I found it, can answer it, and am reasonably confident that, unless you used the sample code provided by the Apple Developer Connection web site that does what you're asking, you still need answer. I base that solely on this fact: it's hard to figure out.
Nonetheless, I have a basic, working project that addresses your question; however, before looking at it, check out a video I made of it running on my iPhone 6s Plus:
<iframe width="640" height="360" src="https://www.youtube.com/embed/GiF-FFKvy5M?rel=0&controls=0&showinfo=0" frameborder="0" allowfullscreen></iframe>
As you can see, the poster frame for every asset in my iPhone's video collection is displayed in UICollectionViewCell; in the UICollectionViewController (or the UICollectionView / datasource delegate:
void (^renderThumbnail)(NSIndexPath *, CustomCell *) = ^(NSIndexPath *indexPath, CustomCell *cell) {
[[PHImageManager defaultManager] requestAVAssetForVideo:AppDelegate.assetsFetchResults[indexPath.section] options:nil resultHandler:^(AVAsset * _Nullable asset, AVAudioMix * _Nullable audioMix, NSDictionary * _Nullable info) {
cell.asset = [asset copy];
cell.frameTime = [NSValue valueWithCMTime:kCMTimeZero];
}];
};
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
PHAsset *phAsset = AppDelegate.assetsFetchResults[indexPath.section];
CustomCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:CellReuseIdentifier forIndexPath:indexPath];
cell.representedAssetIdentifier = phAsset.localIdentifier;
CGFloat hue = (CGFloat)indexPath.section / 5;
cell.backgroundColor = [UIColor colorWithHue:hue saturation:1.0f brightness:0.5f alpha:1.0f];
if ([cell.representedAssetIdentifier isEqualToString:phAsset.localIdentifier]) {
NSPurgeableData *data = [self.thumbnailCache objectForKey:phAsset.localIdentifier];
[data beginContentAccess];
UIImage *image = [UIImage imageWithData:data];
if (image != nil) {
cell.contentView.layer.contents = (__bridge id)image.CGImage;
NSLog(#"Cached image found");
} else {
renderThumbnail(indexPath, cell);
}
[data endContentAccess];
[data discardContentIfPossible];
}
// Request an image for the asset from the PHCachingImageManager.
/*[AppDelegate.imageManager requestImageForAsset:phAsset
targetSize:cell.contentView.bounds.size
contentMode:PHImageContentModeAspectFill
options:nil
resultHandler:^(UIImage *result, NSDictionary *info) {
// Set the cell's thumbnail image if it's still showing the same asset.
if ([cell.representedAssetIdentifier isEqualToString:phAsset.localIdentifier]) {
cell.thumbnailImage = result;
}
}];*/
return cell;
}
In the UICollectionViewCell subclass:
#implementation CustomCell
- (void)prepareForReuse {
[super prepareForReuse];
_asset = nil;
_frameTime = nil;
_thumbnailImage = nil;
[self.contentView.layer setContents:nil];
[[self contentView] setContentMode:UIViewContentModeScaleAspectFit];
[[self contentView] setClipsToBounds:YES];
}
- (void)dealloc {
}
- (void)setAsset:(AVAsset *)asset {
_asset = asset;
}
- (void)setFrameTime:(NSValue *)frameTime {
_frameTime = frameTime;
dispatch_queue_t concurrentQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0);
dispatch_async(concurrentQueue, ^{
AVAssetImageGenerator *imageGenerator = [AVAssetImageGenerator assetImageGeneratorWithAsset:_asset];
imageGenerator.appliesPreferredTrackTransform = YES;
imageGenerator.requestedTimeToleranceAfter = kCMTimeZero;
imageGenerator.requestedTimeToleranceBefore = kCMTimeZero;
[imageGenerator generateCGImagesAsynchronouslyForTimes:#[frameTime] completionHandler:^(CMTime requestedTime, CGImageRef _Nullable image, CMTime actualTime, AVAssetImageGeneratorResult result, NSError * _Nullable error) {
dispatch_sync(dispatch_get_main_queue(), ^{
self.thumbnailImage = [UIImage imageWithCGImage:image scale:25.0 orientation:UIImageOrientationUp];
});
}];
});
}
- (void)setThumbnailImage:(UIImage *)thumbnailImage {
_thumbnailImage = thumbnailImage;
self.contentView.layer.contents = (__bridge id)_thumbnailImage.CGImage;
}
#end
The NSCache is set up like this:
self.thumbnailCache = [[NSCache alloc] init];
self.thumbnailCache.name = #"Thumbnail Cache";
self.thumbnailCache.delegate = self;
self.thumbnailCache.evictsObjectsWithDiscardedContent = true;
self.thumbnailCache.countLimit = AppDelegate.assetsFetchResults.count;
The PHAssets were acquired this way:
- (PHFetchResult *)assetsFetchResults {
__block PHFetchResult *i = self->_assetsFetchResults;
if (!i) {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
PHFetchResult *smartAlbums = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum subtype:PHAssetCollectionSubtypeSmartAlbumVideos options:nil];
self->_assetCollection = smartAlbums.firstObject;
if (![self->_assetCollection isKindOfClass:[PHAssetCollection class]]) self->_assetCollection = nil;
PHFetchOptions *allPhotosOptions = [[PHFetchOptions alloc] init];
allPhotosOptions.sortDescriptors = #[[NSSortDescriptor sortDescriptorWithKey:#"creationDate" ascending:NO]];
i = [PHAsset fetchAssetsInAssetCollection:self->_assetCollection options:allPhotosOptions];
self->_assetsFetchResults = i;
});
}
return i;
}
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.
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;
I want to get the list of all video files which are stored in iPhone internally (recorded and iPod). I want to show all the video files in my application.
I have a TableViewController and want to show all video file from iphone in my application.
How can I get a list of all the video files?
You have to use assetLibraries Try this code :-
- (void)updateAssetsLibrary
{
loadImgView.hidden = NO;
[spinner startAnimating];
//selectVideoBtn .userInteractionEnabled = NO;
assetItems = [NSMutableArray arrayWithCapacity:0];
ALAssetsLibrary *assetLibrary = assetsLibrary;
[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];
appDelegate.videoURL = [[asset valueForProperty:ALAssetPropertyURLs] valueForKey:uti];
mpVideoPlayer = [[MPMoviePlayerController alloc] initWithContentURL:appDelegate.videoURL];
NSString *title = [NSString stringWithFormat:#"%# %i", NSLocalizedString(#"Video", nil), [assetItems count]+1];
[self performSelector:#selector(imageFromVideoURL)];
[dic setValue:title forKey:kName];
[dic setValue:appDelegate.videoURL forKey:kURL];
AssetBrowserItem *item = [[AssetBrowserItem alloc] initWithURL:appDelegate.videoURL title:title];
[assetItems addObject:item];
[appDelegate.videoURLArray addObject:dic];
NSLog(#"Video has info:%#",appDelegate.videoURLArray);
}
NSLog(#"Values of dictonary==>%#", dic);
//NSLog(#"assetItems:%#",assetItems);
NSLog(#"Videos Are:%#",appDelegate.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
{
// result
UIImage *image = nil;
// AVAssetImageGenerator
AVAsset *asset = [[AVURLAsset alloc] initWithURL:appDelegate.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:kImage];
NSLog(#"Values of dictonary==>%#", dic);
NSLog(#"Videos Are:%#",appDelegate.videoURLArray);
CGImageRelease(halfWayImage);
}
return image;
}
- (void)assetsLibraryDidChange:(NSNotification*)changeNotification
{
[self updateAssetsLibrary];
}
- (void)buildAssetsLibrary
{
assetsLibrary = [[ALAssetsLibrary alloc] init];
ALAssetsLibrary *notificationSender = nil;
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];
}
This code will give u list of videos of your iPhone.
It may help you Thankss :)
Get List of all Video and Thumbnails
With the help of above answer I got it working..
Thanks to #Nikhil Bansal,
it helped me, but still it required couple of hours to make the code executable as he is missing few things in his answer
So I would like to share my full working code
1.just add frameworks AssetsLibrary, AVFoundation and MediaPlayer.
2.AssetBrowserItem.h and AssetBrowserItem.m here
3.use below code to get list of all videos from ios device lib
4.run app and see Log for videos details
#import "HomeViewController.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import <MediaPlayer/MediaPlayer.h>
#import <AVFoundation/AVFoundation.h>
#import "AssetBrowserItem.h"
#interface HomeViewController ()
#property (nonatomic, strong) ALAssetsLibrary *assetsLibrary;
#property (nonatomic, strong) NSURL *videoURL;
#property (nonatomic, strong) MPMoviePlayerController *mpVideoPlayer;
#property (nonatomic, strong) NSMutableArray *videoURLArray;
#property (nonatomic, strong) NSMutableArray *assetItems;
#property (nonatomic, strong) NSMutableDictionary *dic;
#end
#implementation HomeViewController
#synthesize assetsLibrary, assetItems,dic;
#synthesize videoURL,videoURLArray, mpVideoPlayer;
- (void)viewDidLoad
{
[super viewDidLoad];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
#pragma mark - Show Video List Methods
- (IBAction)showVideoList:(id)sender
{
[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 = assetsLibrary;
[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;
}
#end