ios8 - vacios - eliminar album personas iphone
Marco iOS 8 Photos: obtenga una lista de todos los álbumes con iOS8 (3)
¿Cómo obtengo una lista de todas las colecciones, incluido el carrete de la cámara (que ahora se llama momentos), en iOS8?
En iOS 7, utilizo el bloque de enumeración ALAssetGroup, pero eso no incluye los momentos de iOS que parece ser equivalente a Camera Roll en iOS7.
void (^assetGroupEnumerator)(ALAssetsGroup *, BOOL *) = ^(ALAssetsGroup *group, BOOL *stop)
{
if (group == nil) {// We''re done enumerating
return;
}
[group setAssetsFilter:[ALAssetsFilter allAssets]];
if ([[sGroupPropertyName lowercaseString] isEqualToString:@"camera roll"] && nType == ALAssetsGroupSavedPhotos) {
[_assetGroups insertObject:group atIndex:0];
} else {
[_assetGroups addObject:group];
}
};
// Group Enumerator Failure Block
void (^assetGroupEnumberatorFailure)(NSError *) = ^(NSError *error) {
SMELog(@"Enumeration occured %@", [error description]);
};
// Enumerate Albums
[_library enumerateGroupsWithTypes:kSupportedALAlbumsMask
usingBlock:assetGroupEnumerator
failureBlock:assetGroupEnumberatorFailure];
}];
Esto es simplemente una traducción de la excelente respuesta aceptada de @ Ladislav a Swift:
// *** 1 ***
// Get all photos (Moments in iOS8, or Camera Roll before)
// Optionally if you want them ordered as by creation date, you just add PHFetchOptions like so:
let allPhotosOptions = PHFetchOptions()
allPhotosOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: true)]
let allPhotosResult = PHAsset.fetchAssetsWithMediaType(PHAssetMediaType.Image, options: allPhotosOptions)
// Now if you want you can get assets from the PHFetchResult object:
allPhotosResult.enumerateObjectsUsingBlock({ print("Asset /($0.0)") })
// *** 2 ***
// Get all user albums (with additional sort for example to only show albums with at least one photo)
let userAlbumsOptions = PHFetchOptions()
userAlbumsOptions.predicate = NSPredicate(format: "estimatedAssetCount > 0")
let userAlbums = PHAssetCollection.fetchAssetCollectionsWithType(PHAssetCollectionType.Album, subtype: PHAssetCollectionSubtype.Any, options: userAlbumsOptions)
userAlbums.enumerateObjectsUsingBlock( {
if let collection = $0.0 as? PHAssetCollection {
print("album title: /(collection.localizedTitle)")
//For each PHAssetCollection that is returned from userAlbums: PHFetchResult you can fetch PHAssets like so (you can even limit results to include only photo assets):
let onlyImagesOptions = PHFetchOptions()
onlyImagesOptions.predicate = NSPredicate(format: "mediaType = %i", PHAssetMediaType.Image.rawValue)
if let result = PHAsset.fetchKeyAssetsInAssetCollection(collection, options: onlyImagesOptions) {
print("Images count: /(result.count)")
}
}
} )
// *** 3 ***
// Get smart albums
let smartAlbums = PHAssetCollection.fetchAssetCollectionsWithType(.SmartAlbum, subtype: .AlbumRegular, options: nil) // Here you can specify Photostream, etc. as PHAssetCollectionSubtype.xxx
smartAlbums.enumerateObjectsUsingBlock( {
if let assetCollection = $0.0 as? PHAssetCollection {
print("album title: /(assetCollection.localizedTitle)")
// One thing to note with Smart Albums is that collection.estimatedAssetCount can return NSNotFound if estimatedAssetCount cannot be determined. As title suggest this is estimated. If you want to be sure of number of assets you have to perform fetch and get the count like:
let assetsFetchResult = PHAsset.fetchAssetsInAssetCollection(assetCollection, options: nil)
let numberOfAssets = assetsFetchResult.count
let estimatedCount = (assetCollection.estimatedAssetCount == NSNotFound) ? -1 : assetCollection.estimatedAssetCount
print("Assets count: /(numberOfAssets), estimate: /(estimatedCount)")
}
} )
Prueba este código ...
self.imageArray = [[NSArray 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:countValue];
// 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];
}];
self.imageArray = [images copy];
Usar Photos Framework es un poco diferente, puedes lograr el mismo resultado, solo tienes que hacerlo en partes.
1) Obtenga todas las fotos (Momentos en iOS8 o Camera Roll antes)
PHFetchResult *allPhotosResult = [PHAsset fetchAssetsWithMediaType:PHAssetMediaTypeImage options:nil];
Opcionalmente, si desea ordenarlos como por fecha de creación, simplemente agregue PHFetchOptions
manera:
PHFetchOptions *allPhotosOptions = [PHFetchOptions new];
allPhotosOptions.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:YES]];
PHFetchResult *allPhotosResult = [PHAsset fetchAssetsWithMediaType:PHAssetMediaTypeImage options:allPhotosOptions];
Ahora, si lo desea, puede obtener activos del objeto PHFetchResult
:
[allPhotosResult enumerateObjectsUsingBlock:^(PHAsset *asset, NSUInteger idx, BOOL *stop) {
NSLog(@"asset %@", asset);
}];
2) Obtenga todos los álbumes de los usuarios (con clasificación adicional, por ejemplo, para mostrar solo álbumes con al menos una foto)
PHFetchOptions *userAlbumsOptions = [PHFetchOptions new];
userAlbumsOptions.predicate = [NSPredicate predicateWithFormat:@"estimatedAssetCount > 0"];
PHFetchResult *userAlbums = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAny options:userAlbumsOptions];
[userAlbums enumerateObjectsUsingBlock:^(PHAssetCollection *collection, NSUInteger idx, BOOL *stop) {
NSLog(@"album title %@", collection.localizedTitle);
}];
Para cada PHAssetCollection
que se devuelve desde PHFetchResult *userAlbums
, puede obtener los PHAssets
manera (incluso puede limitar los resultados para incluir solo activos de fotos):
PHFetchOptions *onlyImagesOptions = [PHFetchOptions new];
onlyImagesOptions.predicate = [NSPredicate predicateWithFormat:@"mediaType = %i", PHAssetMediaTypeImage];
PHFetchResult *result = [PHAsset fetchAssetsInAssetCollection:collection options:onlyImagesOptions];
3) Consigue álbumes inteligentes
PHFetchResult *smartAlbums = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];
[smartAlbums enumerateObjectsUsingBlock:^(PHAssetCollection *collection, NSUInteger idx, BOOL *stop) {
NSLog(@"album title %@", collection.localizedTitle);
}];
Una cosa a tener en cuenta con los álbumes inteligentes es que collection.estimatedAssetCount
puede devolver NSNotFound
si no se puede determinar la estimación de NSNotFound
. Como el título sugiere que esto es estimado. Si quiere estar seguro de la cantidad de activos que debe realizar, obtenga y cuente como:
PHFetchResult *assetsFetchResult = [PHAsset fetchAssetsInAssetCollection:assetCollection options:nil];
número de activos = assetsFetchResult.count
Apple tiene un proyecto de muestra que hace lo que quiere:
https://developer.apple.com/library/content/samplecode/UsingPhotosFramework/ExampleappusingPhotosframework.zip (debe ser un desarrollador registrado para acceder a este)