Quiero obtener todas las fotos de photoLibrary. Preferiría un método o ejemplo que pueda usar directamente.¿Obtiene todas las imágenes de una PhotoBiblioteca de iPhone en una matriz utilizando AssetsLibrary framework?
Respuesta
// cabecera Vista Controlador archivo (.h) ..
#import <UIKit/UIKit.h>
#include <AssetsLibrary/AssetsLibrary.h>
@interface getPhotoLibViewController : UIViewController
{
ALAssetsLibrary *library;
NSArray *imageArray;
NSMutableArray *mutableArray;
}
-(void)allPhotosCollected:(NSArray*)imgArray;
@end
// aplicación archivo
declaran variable de recuento global como
métodostatic int count=0;
@implementation getPhotoLibViewController
-(void)getAllPictures
{
imageArray=[[NSArray alloc] init];
mutableArray =[[NSMutableArray alloc]init];
NSMutableArray* assetURLDictionaries = [[NSMutableArray alloc] init];
library = [[ALAssetsLibrary alloc] init];
void (^assetEnumerator)(ALAsset *, NSUInteger, BOOL *) = ^(ALAsset *result, NSUInteger index, BOOL *stop) {
if(result != nil) {
if([[result valueForProperty:ALAssetPropertyType] isEqualToString:ALAssetTypePhoto]) {
[assetURLDictionaries addObject:[result valueForProperty:ALAssetPropertyURLs]];
NSURL *url= (NSURL*) [[result defaultRepresentation]url];
[library assetForURL:url
resultBlock:^(ALAsset *asset) {
[mutableArray addObject:[UIImage imageWithCGImage:[[asset defaultRepresentation] fullScreenImage]]];
if ([mutableArray count]==count)
{
imageArray=[[NSArray alloc] initWithArray:mutableArray];
[self allPhotosCollected:imageArray];
}
}
failureBlock:^(NSError *error){ NSLog(@"operation was not successfull!"); } ];
}
}
};
NSMutableArray *assetGroups = [[NSMutableArray alloc] init];
void (^ assetGroupEnumerator) (ALAssetsGroup *, BOOL *)= ^(ALAssetsGroup *group, BOOL *stop) {
if(group != nil) {
[group enumerateAssetsUsingBlock:assetEnumerator];
[assetGroups addObject:group];
count=[group numberOfAssets];
}
};
assetGroups = [[NSMutableArray alloc] init];
[library enumerateGroupsWithTypes:ALAssetsGroupAll
usingBlock:assetGroupEnumerator
failureBlock:^(NSError *error) {NSLog(@"There is an error");}];
}
-(void)allPhotosCollected:(NSArray*)imgArray
{
//write your code here after getting all the photos from library...
NSLog(@"all pictures are %@",imgArray);
}
@end
Uso getAllPicture para obtener fotos de librería fotográfica.
O bien, puede echar un vistazo a este blog http://mutiselectimagepicker.blogspot.in/2014/08/imageselect-to-allow-multiple-selection.html
¡La huella de memoria del enfoque anterior es tremenda! Aunque es una forma muy fácil y sencilla de hacerlo. La administración de la memoria específicamente se vuelve difícil debido al uso de un bloque asíncrono. –
Da error, si usamos "# include
importación import
-(void)getFromGallery:(BOOL)IsImages
{
if(self.csCollectionsArray != nil)
[self.csCollectionsArray removeAllObjects];
__block NSMutableDictionary *date = [[NSMutableDictionary alloc] init];
ALAssetsLibrary *csAssetsLibrary = [[ALAssetsLibrary alloc] init];
NSUInteger groupTypes = ALAssetsGroupAlbum | ALAssetsGroupEvent | ALAssetsGroupFaces | ALAssetsGroupSavedPhotos;
[csAssetsLibrary enumerateGroupsWithTypes:groupTypes usingBlock:^(ALAssetsGroup *group, BOOL *stop)
{
if([group numberOfAssets] > 0)
{
if(IsImages)
[group setAssetsFilter:[ALAssetsFilter allPhotos]];
else
[group setAssetsFilter:[ALAssetsFilter allVideos]];
[group enumerateAssetsWithOptions:NSEnumerationReverse usingBlock:^(ALAsset *asset, NSUInteger index, BOOL *stop)
{
if(asset)
{ //1.fetching all assets from device library
//2.Add all fetched assests from library
[date setObject:asset forKey:[asset valueForProperty:ALAssetPropertyDate]];
}
}];
}
else
{ NSLog(@"---> load table -------->");
if(date != nil && date.count > 0)
{ //3.Sort using date by ascending order and moved to dictionary to array
NSArray *sortedKeys = [[date allKeys] sortedArrayUsingSelector: @selector(compare:)];
for (NSString *key in sortedKeys)
[self.csCollectionsArray addObject: [date objectForKey:key]];
//4.Load images into collection view after fetching all datas
[self reloadCollectionView];
if(self.csCollectionView != nil)
[self.csCollectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:([self.csCollectionsArray count] - 1) inSection:0] atScrollPosition:UICollectionViewScrollPositionBottom animated:YES];
}
date = nil;
}
}failureBlock:^(NSError *error)
{
if((csCollectionsArray == nil || [csCollectionsArray count] == 0))
{
ALAuthorizationStatus status = [ALAssetsLibrary authorizationStatus]; if(status != ALAuthorizationStatusAuthorized)
{
[self showAlertAndCloseUploaderView:@"You can just go to \"Settings\" app (General -> Reset -> Reset Location & Privacy) then come again and click ok when the alert dialog is showing for enable the permission to access the photo library"];
}
}
}];
}
Puede utilizar este método de abajo a buscar todas las imágenes o vídeos desde la biblioteca de activos en ios. uso de este marco assetslibrary (mosto) NOTA: - import
-(void)getFromGallery:(BOOL)IsImages
{
if(self.csCollectionsArray != nil)
[self.csCollectionsArray removeAllObjects];
__block NSMutableDictionary *date = [[NSMutableDictionary alloc] init];
ALAssetsLibrary *csAssetsLibrary = [[ALAssetsLibrary alloc] init];
NSUInteger groupTypes = ALAssetsGroupAlbum | ALAssetsGroupEvent | ALAssetsGroupFaces | ALAssetsGroupSavedPhotos;
[csAssetsLibrary enumerateGroupsWithTypes:groupTypes usingBlock:^(ALAssetsGroup *group, BOOL *stop)
{
if([group numberOfAssets] > 0)
{
if(IsImages)
[group setAssetsFilter:[ALAssetsFilter allPhotos]];
else
[group setAssetsFilter:[ALAssetsFilter allVideos]];
[group enumerateAssetsWithOptions:NSEnumerationReverse usingBlock:^(ALAsset *asset, NSUInteger index, BOOL *stop)
{
if(asset)
{ //1.fetching all assets from device library
//2.Add all fetched assests from library
[date setObject:asset forKey:[asset valueForProperty:ALAssetPropertyDate]];
}
}];
}
else
{ NSLog(@"---> load table -------->");
if(date != nil && date.count > 0)
{ //3.Sort using date by ascending order and moved to dictionary to array
NSArray *sortedKeys = [[date allKeys] sortedArrayUsingSelector: @selector(compare:)];
for (NSString *key in sortedKeys)
[self.csCollectionsArray addObject: [date objectForKey:key]];
//4.Load images into collection view after fetching all datas
[self reloadCollectionView];
if(self.csCollectionView != nil)
[self.csCollectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:([self.csCollectionsArray count] - 1) inSection:0] atScrollPosition:UICollectionViewScrollPositionBottom animated:YES];
}
date = nil;
}
}failureBlock:^(NSError *error)
{
if((csCollectionsArray == nil || [csCollectionsArray count] == 0))
{
ALAuthorizationStatus status = [ALAssetsLibrary authorizationStatus]; if(status != ALAuthorizationStatusAuthorized)
{
[self showAlertAndCloseUploaderView:@"You can just go to \"Settings\" app (General -> Reset -> Reset Location & Privacy) then come again and click ok when the alert dialog is showing for enable the permission to access the photo library"];
}
}
}];
}
Desde ALAssetsLibrary
es obsoleto y ahora Photo Framework
es nueva. Hice mi propia función en Objective C
para obtener todas las fotos de cámara de rollo y almacenar en NSArray
y exhibidas en mi CollectionView
NSArray *imageArray;
NSMutableArray *mutableArray;
-(void)getAllPhotosFromCamera
{
imageArray=[[NSArray alloc] init];
mutableArray =[[NSMutableArray alloc]init];
PHImageRequestOptions *requestOptions = [[PHImageRequestOptions alloc] init];
requestOptions.resizeMode = PHImageRequestOptionsResizeModeExact;
requestOptions.deliveryMode = PHImageRequestOptionsDeliveryModeHighQualityFormat;
requestOptions.synchronous = true;
PHFetchResult *result = [PHAsset fetchAssetsWithMediaType:PHAssetMediaTypeImage options:nil];
NSLog(@"%d",(int)result.count);
PHImageManager *manager = [PHImageManager defaultManager];
NSMutableArray *images = [NSMutableArray arrayWithCapacity:[result count]];
// assets contains PHAsset objects.
__block UIImage *ima;
for (PHAsset *asset in result) {
// Do something with the asset
[manager requestImageForAsset:asset
targetSize:PHImageManagerMaximumSize
contentMode:PHImageContentModeDefault
options:requestOptions
resultHandler:^void(UIImage *image, NSDictionary *info) {
ima = image;
[images addObject:ima];
}];
}
imageArray = [images copy]; // You can direct use NSMutuable Array images
}
- 1. ¿Obtiene todas las permutaciones de una matriz de PHP?
- 2. Conseguir todas las combinaciones en una matriz
- 3. recortar todas las cadenas en una matriz
- 4. Devolución de todas las imágenes en una página de Wikipedia
- 5. ¿Cómo se obtiene una lista de todas las fuentes instaladas?
- 6. Al insertar una cadena en una matriz dentro de una matriz se obtiene un resultado inesperado
- 7. Cargar y mostrar todas las imágenes de una carpeta
- 8. Obtenga todas las combinaciones posibles de caracteres en una matriz
- 9. Obtener todas las filas seleccionadas de mysql en una matriz
- 10. JavaScript: ¿cómo cargar todas las imágenes en una carpeta?
- 11. Imágenes SVG en una aplicación de iPhone
- 12. Eliminar todas las imágenes
- 13. iPhone - Impresión de varias imágenes en una hoja
- 14. ¿Todas las imágenes de la tienda son las imágenes base, pequeñas y en miniatura de Magento?
- 15. Listar todas las imágenes de la cámara en Android
- 16. Lista de todas las imágenes de fondo en DOM
- 17. Eliminar todas las entidades en Entity Framework
- 18. Reflejo de Javascript: ¿obtiene todas las propiedades de un objeto?
- 19. Generar una matriz de todas las letras y dígitos
- 20. cómo ordenar una matriz de todas las columnas
- 21. buscando todas las series dentro de una matriz
- 22. Crear una matriz de todas las variables GET
- 23. Javascript: Obtener todas las claves existentes en una matriz JSON
- 24. PHP Obtenga todas las claves numéricas/anónimas en una matriz
- 25. Obtener todas las imágenes url de cadena
- 26. Mostrando una imagen de una matriz de imágenes - Javascript
- 27. Completar una matriz utilizando un bucle foreach
- 28. Obtener una matriz de imágenes en UIImageView (en UIPageViewController)
- 29. Obtención de todas las variables globales (javascript) en una página
- 30. ¿Es posible crear una fila que abarque todas las columnas de una matriz en SSRS 2008?
Por favor, intente esto por una vez .. http://stackoverflow.com/a/38992502/3908884 –