How to get videos from iPhone without using asset library? - ios

- (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.

Related

Not getting the value in asset when loading the video from gallery using ALAssetLibrary

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

How to list all videos from user device

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?

Stream audio to other iOS devices (using multipeer) AND play audio through local device

Basically I'm streaming audio to other iOS devices through multipeer connectivity. I am using this tutorial, and right now I can stream music to other devices and have the other devices play the music. However, my local device host doesn't play the music. In order to do this, I basically tried
- (void)mediaPicker:(MPMediaPickerController *)mediaPicker didPickMediaItems:(MPMediaItemCollection *)mediaItemCollection
{
self.outputStreamer = [[TDAudioOutputStreamer alloc] initWithOutputStream:[self.session outputStreamForPeer:peers[0]]];
[self.outputStreamer streamAudioFromURL:[self.song valueForProperty:MPMediaItemPropertyAssetURL]];
[self.outputStreamer start];
self.player = [[AVAudioPlayer alloc] initWithContentsOfURL:[self.song valueForProperty:MPMediaItemPropertyAssetURL]error: NULL];
[self.player play];
peers is an array of connected peers, everything is working fine with that. If I comment out the last two lines (the AVAudioPlayer), then the streaming to other devices works, vice versa. It seems like I can only do one or the other. (self.player is declared in the .h, it is fine.)
Any solution to this double audio playing? Thanks in advance.
You have to create object of
TDAudioInputStreamer
on client end too.
self.inputStream = [[TDAudioInputStreamer alloc] initWithInputStream:stream];
[self.inputstream start];
When you create output stream.
you can pick your song with media picker then need to convert your assets
**- (void)mediaPicker:(MPMediaPickerController *)mediaPicker didPickMediaItems:(MPMediaItemCollection *)mediaItemCollection
`
----------
-
`**
[self dismissViewControllerAnimated:YES completion:nil];
someMutableArray = [mediaItemCollection items];
NSLog(#"%#",someMutableArray);
MPMediaItem *song=[mediaItemCollection.items objectAtIndex:0];
NSString * type = [song valueForProperty:MPMediaItemPropertyMediaType];
NSURL * url = [song valueForProperty:MPMediaItemPropertyAssetURL];
NSDictionary*dict=[[NSDictionary alloc] init];
AVAsset *asset = [AVAsset assetWithURL:url];
NSArray * metadata = [asset commonMetadata];
NSArray * metadata1 = [asset metadata];
NSArray * metadata2 = [asset availableMetadataFormats];
NSMutableDictionary *info = [NSMutableDictionary dictionary];
info[#"title"] = [song valueForProperty:MPMediaItemPropertyTitle] ? [song valueForProperty:MPMediaItemPropertyTitle] : #"";
info[#"artist"] = [song valueForProperty:MPMediaItemPropertyArtist] ? [song valueForProperty:MPMediaItemPropertyArtist] : #"";
NSNumber *duration=[song valueForProperty:MPMediaItemPropertyPlaybackDuration];
int fullminutes = floor([duration floatValue] / 60); // fullminutes is an int
int fullseconds = trunc([duration floatValue] - fullminutes * 60); // fullseconds is an int
info[#"duration"] = [NSString stringWithFormat:#"%d:%d", fullminutes, fullseconds];
MPMediaItemArtwork *artwork = [song valueForProperty:MPMediaItemPropertyArtwork];
UIImage *image = [artwork imageWithSize:CGSizeMake(150, 150)];
NSData * data = UIImageJPEGRepresentation(image, 0.0);
image = [UIImage imageWithData:data];
if (image)
self.songArtWorkImageView.image = image;
else
self.songArtWorkImageView.image = nil;
self.songTitleLbl.text = [NSString stringWithFormat:#"%# \n[Artist : %#]", info[#"title"], info[#"artist"]];
[_session sendData:[NSKeyedArchiver archivedDataWithRootObject:[info copy]] toPeers:_session.connectedPeers withMode:MCSessionSendDataReliable error: nil];
#try {
if(_session && _session.connectedPeers && [_session.connectedPeers count] > 0) {
for(int i=0;i<someMutableArray.count;i++){
MPMediaItem *song = [someMutableArray objectAtIndex:i];
for(int i=0;i<someMutableArray.count;i++){
MPMediaItem *song = [someMutableArray objectAtIndex:i];
AVURLAsset *asset = [AVURLAsset URLAssetWithURL:[song valueForProperty:MPMediaItemPropertyAssetURL] options:nil];
[self convertAsset: asset complition:^(BOOL Success, NSString *filePath) {
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
if(Success) {
if(image) {
[self saveImage: image withComplition:^(BOOL status, NSString *imageName, NSURL *imageURL) {
if(status) {
#try {
[_session sendResourceAtURL:imageURL withName:imageName toPeer:[_session.connectedPeers objectAtIndex:0] withCompletionHandler:^(NSError *error) {
if (error) {
NSLog(#"Failed to send picture to %#", error.localizedDescription);
return;
}
//Clean up the temp file
NSFileManager *fileManager = [NSFileManager defaultManager];
[fileManager removeItemAtURL:imageURL error:nil];
}];
}
#catch (NSException *exception) {
}
}
}];
}
#try {
if(!self.outputStream) {
NSArray * connnectedPeers = [_session connectedPeers];
if([connnectedPeers count] != 0) {
[self outputStreamForPeer:[_session.connectedPeers objectAtIndex:0]];
}
}
}
#catch (NSException *exception) {
}
if(self.outputStream) {
if(!self.outputStreamer) {
self.outputStreamer = [[TDAudioOutputStreamer alloc] initWithOutputStream:self.outputStream];
}
[self.outputStreamer initStream:filePath];
if(self.outputStreamer) {
[self.outputStreamer start];
}
}
}
else {
[UIView showMessageWithTitle:#"Error!" message:#"Error occured!" showInterval:1.5];
}
});
}];
}
}
}
}
#catch (NSException *exception) {
NSLog(#"Expection: %#", [exception debugDescription]);
}
}

How to display video from ALAsset to UICollectionview ios

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.

How to get the list of all video files in iPhone

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

Resources