This is deprecated, what could be the updated code?
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
[library assetForURL:referenceURL resultBlock:^(ALAsset *asset) {
ALAssetRepresentation *rep = [asset defaultRepresentation];
Use below code to get all picture from Gallery:
First you need to import Photo framework.
#import <Photos/Photos.h>
Take Authorization before getting image:
[PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status)
{
switch (status) {
case PHAuthorizationStatusAuthorized:
[self performSelectorOnMainThread:#selector(getAllPictures) withObject:nil waitUntilDone:NO];
// [self getAllPictures];
NSLog(#"PHAuthorizationStatusAuthorized");
break;
case PHAuthorizationStatusRestricted:
NSLog(#"PHAuthorizationStatusRestricted");
break;
case PHAuthorizationStatusDenied:
NSLog(#"PHAuthorizationStatusDenied");
break;
default:
break;
}
}];
-(void)getAllPicture
{
NSLog(#"Started...");
PHImageRequestOptions *requestOptions = [[PHImageRequestOptions alloc] init];
requestOptions.synchronous = YES;
PHFetchOptions *allPhotosOptions = [PHFetchOptions new];
allPhotosOptions.sortDescriptors = #[[NSSortDescriptor sortDescriptorWithKey:#"creationDate" ascending:YES]];
PHFetchResult *result = [PHAsset fetchAssetsWithMediaType:PHAssetMediaTypeImage options:allPhotosOptions];
for (PHAsset *asset in result) {
NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
[dic setValue:asset forKey:#"assest"];
[YOUR_ARRAY insertObject:dic atIndex:0];
dic = nil;
}
NSLog(#"Completed...");
}
You can retrive image from below code:
PHImageRequestOptions *requestOptions = [[PHImageRequestOptions alloc] init];
requestOptions.synchronous = YES;
PHImageManager *manager = [PHImageManager defaultManager];
[manager requestImageForAsset:YOUR_ARRAY[INDEX_ARRAY][#"assest"]
targetSize:CGSizeMake(self.view.frame.size.width/3, 200)
contentMode:PHImageContentModeDefault
options:requestOptions
resultHandler:^void(UIImage *image, NSDictionary *info) {
YOUR_IMAGE_VIEW.image = image;
}];
Related
Im using the following code to access filename of the image that I gotta upload. I need both filename alongside the file path and size.
ALAssetsLibraryAssetForURLResultBlock resultblock = ^(ALAsset *imageAsset)
{
ALAssetRepresentation *imageRep = [imageAsset defaultRepresentation];
NSLog(#"[imageRep filename] : %#", [imageRep filename]);
[_imageNameArray addObject:[imageRep filename]];
};
[_uploadTbleView reloadData];
ALAssetsLibrary* assetslibrary = [[ALAssetsLibrary alloc] init];
[assetslibrary assetForURL:refURL resultBlock:resultblock failureBlock:nil];
The problem that Im facing is,
Xcode throws a warning message that ALAssetsLibraryAssetForURLResultBlock is deprecated. How can I replace the above code to get the filename ?
I tried using PHAsset but every time when Im selecting the file, it has got the same file name called asset.jpg for all image files.
You can try this:
PHAsset *asset = nil;
PHFetchOptions *fetchOptions = [[PHFetchOptions alloc] init];
fetchOptions.sortDescriptors = #[[NSSortDescriptor sortDescriptorWithKey:#"creationDate" ascending:YES]];
PHFetchResult *fetchResult = [PHAsset fetchAssetsWithMediaType:PHAssetMediaTypeImage options:fetchOptions];
if (fetchResult != nil && fetchResult.count > 0) {
// get last photo from Photos
asset = [fetchResult lastObject];
}
if (asset) {
// get photo info from this asset
PHImageRequestOptions * imageRequestOptions = [[PHImageRequestOptions alloc] init];
imageRequestOptions.synchronous = YES;
[[PHImageManager defaultManager]
requestImageDataForAsset:asset
options:imageRequestOptions
resultHandler:^(NSData *imageData, NSString *dataUTI,
UIImageOrientation orientation,
NSDictionary *info)
{
NSLog(#"info = %#", info);
if ([info objectForKey:#"PHImageFileURLKey"]) {
// path looks like this -
// file:///var/mobile/Media/DCIM/###APPLE/IMG_####.JPG
NSURL *path = [info objectForKey:#"PHImageFileURLKey"];
}
}];
}
I wrote simple library to get photos from camera roll. Unfortunately can't read some of them. I can't preview or convert to NSData
PHFetchOptions *options = [[PHFetchOptions alloc] init];
options.includeAssetSourceTypes = PHAssetSourceTypeUserLibrary;
PHFetchResult *allPhotosResult = [PHAsset fetchAssetsWithMediaType:PHAssetMediaTypeImage options:options];
PHImageRequestOptions *requestOptionForPhotos = [[PHImageRequestOptions alloc] init];
requestOptionForPhotos.networkAccessAllowed = YES;
for(PHAsset *asset in allPhotosResult) {
[[PHImageManager defaultManager]
requestImageForAsset:asset
targetSize:CGSizeMake(100, 100)
contentMode:PHImageContentModeAspectFill
options:requestOptionForPhotos
resultHandler:^(UIImage *result, NSDictionary *info) {
NSData *data = UIImagePNGRepresentation(result);
NSString *base = [data base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed]; // for some of photos there is nil
}];
}
I am using PhotoKit to fetch the photos in one of the system albums like this:
PHFetchOptions *fetchOptions = [[PHFetchOptions alloc] init];
fetchOptions.sortDescriptors = #[[NSSortDescriptor sortDescriptorWithKey:#"creationDate" ascending:YES]];
PHFetchResult *fetchResult = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];
[fetchResult enumerateObjectsUsingBlock:^(PHAssetCollection *collection, NSUInteger idx, BOOL *stop) {
NSLog(#"ALBUM NAME: %#", collection.localizedTitle);
if ([collection.localizedTitle isEqualToString:#"Camera Roll"]) {
PHFetchResult *photos = [PHAsset fetchAssetsInAssetCollection:collection options:nil];
NSLog(#"PHOTOS: %ld", photos.count);
_photos = nil;
_photos = #[].mutableCopy;
for (PHAsset *asset in photos) {
[self loadImageFromPHAsset:asset];
}
}
}];
Then in my custom helper method: (void)loadImageFromPHAsset:(PHAsset *)asset, I have this:
-(void)loadImageFromPHAsset:(PHAsset *)asset
{
PHImageManager *manager = [PHImageManager defaultManager];
CGSize targetSize = _layout.itemSize;
[manager requestImageForAsset:asset targetSize:targetSize contentMode:PHImageContentModeAspectFill options:nil resultHandler:^(UIImage *result, NSDictionary *info) {
[_photos addObject:result];
}];
[self.collectionView reloadData];
}
So I have an array of images and I present them in my UICollectionViewCell:
UIImage *image = [_photos objectAtIndex:indexPath.row];
cell.imageView.contentMode = UIViewContentModeScaleAspectFill;
cell.imageView.image = image;
But what I got is like this, it is very blur, how can I make it clear?
First of all the targetSize should be multiplied by scale to account for the screen's scale like this,
CGFloat scale = [UIScreen mainScreen].scale;
CGSize targetSize = CGSizeMake(_layout.itemSize.width*scale, _layout.itemSize.height*scale);
Secondly, try these options to get the exact size image,
//Async call returned on main thread, can return multiple times
PHImageRequestOptions *options = [[PHImageRequestOptions alloc] init];
options.resizeMode = PHImageRequestOptionsResizeModeExact;
Lastly, if you have performance concerns, use PHCachingManager, I have answered the question regarding performance improvements here
Hope this helps you.
Edit:
I did not realise that the images were stored in an array. Try setting the synchronous flag in image options.
PHImageRequestOptions *options = [[PHImageRequestOptions alloc] init];
options.synchronous = YES;
options.resizeMode = PHImageRequestOptionsResizeModeExact;
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?
- (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.