Am having a Custom folder in my ipad device. Am using this code to get image from Custom album:
self.assetGroups = [[NSMutableArray alloc] init];
// Group enumerator Block
dispatch_async(dispatch_get_main_queue(), ^
{
void (^assetGroupEnumerator)(ALAssetsGroup *, BOOL *) = ^(ALAssetsGroup *group, BOOL *stop)
{
if (group == nil) {
return;
}
if ([[group valueForProperty:ALAssetsGroupPropertyName] isEqualToString:#"Ganesh"]) {
[self.assetGroups addObject:group];
[self loadImages];
return;
}
if (stop) {
return;
}
};
// Group Enumerator Failure Block
void (^assetGroupEnumberatorFailure)(NSError *) = ^(NSError *error) {
UIAlertView * alert = [[UIAlertView alloc]
initWithTitle:#"ERROR" message:[NSString stringWithFormat:#"No Albums Available"]
delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[alert show];
[alert release];
};
// Enumerate Albums
self.library = [[ALAssetsLibrary alloc] init];
[library enumerateGroupsWithTypes:ALAssetsGroupAll
usingBlock:assetGroupEnumerator
failureBlock:assetGroupEnumberatorFailure];
});
To retrieve all the images from my custom folder I am using this:
(void)loadImages {
ALAssetsGroup *assetGroup = [self.assetGroups objectAtIndex:0];
NSLog(#"asserts group %#",self.assetGroups);
NSLog(#"ALBUM NAME:;%#",[assetGroup valueForProperty:ALAssetsGroupPropertyName]);
[assetGroup enumerateAssetsUsingBlock:^(ALAsset *result, NSUInteger index, BOOL *stop){
if(result == nil) {
return;
}
UIImage *img = [UIImage imageWithCGImage:[[result defaultRepresentation] fullScreenImage]
scale:1.0 orientation:(UIImageOrientation)[[result valueForProperty:#"ALAssetPropertyOrientation"] intValue]];
NSLog(#"image name%#",img);
[arrayOfImage addObject:img];
NSLog(#"arrayOfImage %#",arrayOfImage);
// [imageToAnimate setImage:img];
}];
}
its working fine when i am running with simulator but not in device: it executes Failure block and Says No Album Available.
Its works fine. I have switched Off my location service due to this am not able to access my media now it works fine.
Related
Hi I have an video recored output and i want to parse it to the other controller using either blocks or nsnotification center. Here is the code used to get output.
- (void)saveRecordedFile:(NSURL *)recordedFile {
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
ALAssetsLibrary *assetLibrary = [[ALAssetsLibrary alloc] init];
[assetLibrary writeVideoAtPathToSavedPhotosAlbum:recordedFile
completionBlock:
^(NSURL *assetURL, NSError *error) {
dispatch_async(dispatch_get_main_queue(), ^{
NSString *title;
NSString *message;
if (error != nil) {
title = #"Failed to save video";
message = [error localizedDescription];
}
else {
title = #"Saved!";
message = nil;
}
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title
message:message
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
NSLog(#"%#",recordedFile);'
//
}
This output i have to pass to next view controller and from this to time line same like instagram app.
one more thing is already collection view is having images
some body please help me to solve this problem
I'm developing an app where user can record video and save it in the library/or custom album. I'm able to create the custom album and record the video and save it in the default photo library i.e., camera roll.. But i'm unable to save it to the custom album. and other thing is the saved videos in the album must be showed in the collection view of the app i.e., like the gallery view.. so that user can able to click on the videos for the play.. it might be in the grid view/ collection view or might be in the table view where the UIImage should should display the videos saved in the album..
Here's code section which i used in the app development for creating the custom album.
ALAssetsLibrary* libraryFolder = [[ALAssetsLibrary alloc] init];
[libraryFolder addAssetsGroupAlbumWithName:#"HEP" resultBlock:^(ALAssetsGroup *group)
{
NSLog(#"Adding Folder:'My Album', success: %s", group.editable ? "Success" : "Already created: Not Success");
} failureBlock:^(NSError *error)
{
NSLog(#"Error: Adding on Folder");
}];
For recording the video in the app.
- (IBAction)StartRecord:(id)sender {
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
picker.allowsEditing = YES;
picker.sourceType = UIImagePickerControllerSourceTypeCamera;
picker.mediaTypes = [[NSArray alloc] initWithObjects:(NSString *)kUTTypeMovie, nil];
[self presentViewController:picker animated:YES completion:NULL];
}
For saving it in the album i.e., default photo album not the custom album i created.
-(BOOL)startMediaBrowserFromViewController:(UIViewController*)controller usingDelegate:(id )delegate {
// 1 - Validations
if (([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeSavedPhotosAlbum] == NO)
|| (delegate == nil)
|| (controller == nil)) {
return NO;
}
// 2 - Get image picker
UIImagePickerController *mediaUI = [[UIImagePickerController alloc] init];
mediaUI.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
mediaUI.mediaTypes = [[NSArray alloc] initWithObjects: (NSString *) kUTTypeMovie, nil];
// Hides the controls for moving & scaling pictures, or for
// trimming movies. To instead show the controls, use YES.
mediaUI.allowsEditing = YES;
mediaUI.delegate = delegate;
// 3 - Display image picker
[controller presentModalViewController:mediaUI animated:YES];
return YES;
}
Since i'm beginner in iOS still learning.. I'm searching since for a month now. So please help me.
First create your album folder with below code & make sure this code paste in AppDelegate.m file didFinishLaunchingWithOptions method :
ALAssetsLibrary* libraryFolderSozialConnectVideo = [[ALAssetsLibrary alloc] init];
[libraryFolderSozialConnectVideo addAssetsGroupAlbumWithName:#"HEP" resultBlock:^(ALAssetsGroup *group)
{
NSLog(#"HEP Folder Created");
} failureBlock:^(NSError *error) {
NSLog(#"Error: Adding on Folder");
}];
Now, use below function for download your video in HEP folder :
- (void)downloadVideo:(NSURL *)videoURL {
[MBProgressHUD showHUDAddedTo:self.view animated:YES];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSLog(#"Downloading Started");
NSData *urlData = [NSData dataWithContentsOfURL:videoURL];
if (urlData) {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [NSString stringWithFormat:#"%#/%#", documentsDirectory,#"thefile.mp4"];
[urlData writeToFile:filePath atomically:YES];
dispatch_async(dispatch_get_main_queue(), ^{
[MBProgressHUD hideAllHUDsForView:self.view animated:YES];
[self.library saveVideo:[NSURL fileURLWithPath:filePath] toAlbum:#"HEP" completion:^(NSURL *assetURL, NSError *error)
{
NSLog(#"Success downloaded");
} failure:^(NSError *error) {
NSLog(#"Error : %#", [error localizedDescription]);
[MBProgressHUD hideAllHUDsForView:self.view animated:YES];
[self.navigationController popViewControllerAnimated:YES];
}];
});
}
}); }
for videoURL in your didFinishPickingMediaWithInfo method call above function with below code :
self.library = [[ALAssetsLibrary alloc] init];
[self downloadVideo:[info valueForKey:UIImagePickerControllerMediaURL]];
I hope this works . . .
In my app i want to get the image and video from particular album.so i use ALAssetsLibraryGroupsEnumerationResultsBlock function for get the images and video from the particular Album.here i store the asset value in a nsmutablearray,i get that array values on viewdidLoad, but in viewdidload the array value is null.So when ALAssetsLibraryGroupsEnumerationResultsBlock is trigger.
Below is my code help me..
- (void)viewDidLoad {
[super viewDidLoad];
if (self.assetLibrary == nil) {
_assetLibrary = [[ALAssetsLibrary alloc] init];
}
if (self.groups == nil) {
_groups = [[NSMutableArray alloc] init];
} else {
[self.groups removeAllObjects];
}
[self loadAssetImages];
}
-(void)loadAssetImages{
NSLog(#"Load asset Image ");
ALAssetsLibraryAccessFailureBlock failureBlock = ^(NSError *error) {
UIAlertView * alert = [[UIAlertView alloc] initWithTitle:#"ERROR" message:[NSString stringWithFormat:#"No Albums Available"] delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[alert show];
};
ALAssetsLibraryGroupsEnumerationResultsBlock listGroupBlock = ^(ALAssetsGroup *group, BOOL *stop) {
NSLog(#"Block");
if (group == nil)
{
return;
}
if ([[group valueForProperty:ALAssetsGroupPropertyName] isEqualToString:#"FlipDemo"]) {
[self.groups addObject:group];
[self loadImages];
return ;
}
if (stop) {
return;
}
};
NSLog(#"Block Out");
[self.assetLibrary enumerateGroupsWithTypes:ALAssetsGroupAll
usingBlock: listGroupBlock
failureBlock:failureBlock];
}
-(void)loadImages{
NSLog(#"Load Image000");
ALAssetsGroup *assetGroup;
for (assetGroup in self.groups)
{
for (int i = 0; i<[self.groups count]; i++)
{
[ assetGroup enumerateAssetsUsingBlock:^(ALAsset *result, NSUInteger index, BOOL *stop)
{
if (result) {
if ([[result valueForProperty:ALAssetPropertyType] isEqualToString:ALAssetTypeVideo])
{
[videoOnly addObject:result];
}
else if ([[result valueForProperty:ALAssetPropertyType] isEqualToString:ALAssetTypePhoto])
{
[imgOnly addObject:result];
// NSLog(#"Photo");
}
}
}
];
}
}
}
The method is asynchronous. You can find the function detail in help document:
help document
(void)enumerateGroupsWithTypes:(ALAssetsGroupType)types
usingBlock:(ALAssetsLibraryGroupsEnumerationResultsBlock)enumerationBlock
failureBlock:(ALAssetsLibraryAccessFailureBlock)failureBlock
This method is asynchronous. When groups are enumerated, the user may be asked to confirm the application's access to the data; the method, though, returns immediately. You should perform whatever work you want with the assets in enumerationBlock.
end of help document
So, according your code, you can't get anything in your main thread. Because iOS get assets in another thread.
You can set a key-value observation to make main thread waiting for this asynchronous function.
1) set a property, for example: handleOverFindFlag
2) before execute the function: set handleOverFindFlag=NO
3) add Observer
[self addObserver:self forKeyPath:#"handleOverFindFlag" options:0 context:NULL];
4) set observing function:
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:
(NSDictionary *)change context:(void *)context
{
if([keyPath isEqualToString:#""])
{
//handle your findings
}
}
5) after doing this
[self removeObserver:self forKeyPath:#"handleOverFindFlag"];
You can find detail about Key-Value coding in help document.
I am using this code to get the latest photo from the cameraRoll:
- (void) getTheLatestPhoto{
ALAssetsLibrary *cameraRoll = [[ALAssetsLibrary alloc] init];
[cameraRoll enumerateGroupsWithTypes:ALAssetsGroupSavedPhotos usingBlock:^(ALAssetsGroup *images, BOOL *stop) {
[images setAssetsFilter:[ALAssetsFilter allPhotos]];
[images enumerateAssetsAtIndexes:[NSIndexSet indexSetWithIndex:[images numberOfAssets] - 1] options:0 usingBlock:^(ALAsset *result, NSUInteger index, BOOL *stop)
{
if (result) {
ALAssetRepresentation *rep = [result defaultRepresentation];
self.sharingImage = [UIImage imageWithCGImage:[rep fullScreenImage]];
}
}];
}
failureBlock: ^(NSError *error) {
NSLog(#"An error occured: %#",error);
}];
}
As it is, if the library cameraRoll is empty, the app will crash with this error:
Terminating app due to uncaught exception 'NSRangeException', reason: 'indexSet count or lastIndex must not exceed -numberOfAssets'
I understand that my indexSet is higher than the numberOfAssets due to this:
[images enumerateAssetsAtIndexes:[NSIndexSet indexSetWithIndex:[images numberOfAssets] - 1]
At this point my question is "where do I put a condition that allow me to check if the assets is zero?"
If cameraRoll has more than zero, I will let the code continue, but if the count is zero, I would like to handle the issue this way as oppose to let it crash:
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"" message:#"Sorry, there are no photo in Camera Roll" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
Thanks for your help!
Add if([images numberOfAssets]>0) before enumerateAssetsAtIndexes line and continue code...
or if([images numberOfAssets]<=0) then
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"" message:#"Sorry, there are no photo in Camera Roll" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
I am developing an iPad application in which I have saved images to custom album using This.
Now I want to get all the images from that custom folder and I need to show all those in a animated UIImageView.
I know how to set animation but I want to know how to get all the images from particular custom folder.
See this code I used to load the images from the custom album. I have used the same sample code to store my images in custom album.
NSMutableArray *tempArray = [[NSMutableArray alloc] init];
self.assetGroups = tempArray;
library = [[ALAssetsLibrary alloc] init];
// Load Albums into assetGroups
// Group enumerator Block
void (^assetGroupEnumerator)(ALAssetsGroup *, BOOL *) = ^(ALAssetsGroup *group, BOOL *stop)
{
if (group == nil)
{
return;
}
if([[group valueForProperty:ALAssetsGroupPropertyName] isEqualToString:kAlbumName])
{
[self.assetGroups addObject:group];
[self reloadTableView];
return;
}
};
// Group Enumerator Failure Block
void (^assetGroupEnumberatorFailure)(NSError *) = ^(NSError *error) {
CustomAlertView * alert = [[CustomAlertView alloc] initWithTitle:#"Error" message:[NSString stringWithFormat:#"Album Error: %# - %#", [error localizedDescription], [error localizedRecoverySuggestion]] delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[alert show];
NSLog(#"A problem occured %#", [error description]);
};
// Enumerate Albums
[library enumerateGroupsWithTypes:ALAssetsGroupAll
usingBlock:assetGroupEnumerator
failureBlock:assetGroupEnumberatorFailure];
Here the kAlbumName is one string ivar which contains the custom album name.
EDIT:1
Above code just gives you the whole album selected with all it photos now to get those photos from album use the following code
[self.assetGroup enumerateAssetsUsingBlock:^(ALAsset *result, NSUInteger index, BOOL *stop)
{
if(result == nil)
return;
CGRect viewFrames = kThumbSize;//CGRectMake(0, 0, 75, 75);
UIImageView *assetImageView = [[UIImageView alloc] initWithFrame:viewFrames];
[assetImageView setContentMode:UIViewContentModeScaleToFill];
[assetImageView setImage:[UIImage imageWithCGImage:(__bridge CGImageRef)([result originalAsset])]];
}];
NOTE: Instead of kThumbSize define your CGRectMake() as commented.
Enjoy coding :)
Happy Day :)