1.相册访问属性
typedef NS_ENUM(NSInteger, ALAuthorizationStatus) {
ALAuthorizationStatusNotDetermined = 0, // 用户还没有做出选择这个应用程序的问候
ALAuthorizationStatusRestricted, // 这个应用程序没有被授权访问照片数据。当前用户不能改变应用程序的状态,是受限制的。如家长控制权限
ALAuthorizationStatusDenied, // 用户已拒绝该应用程序访问照片数据
ALAuthorizationStatusAuthorized // 用户已授权该应用可以访问照片数据
}
int authorStatus=[ALAssetsLibrary authorizationStatus];
//禁止照片流
//[ALAssetsLibrary disableSharedPhotoStreamsSupport];
2.初始化相册库
ALAssetsLibrary *assetsLibrary=[[ALAssetsLibrary alloc]init];
3.通过url获取asset和group
//通过URL地址获取在相册中ALAsset,该方法是异步的
[assetsLibrary assetForURL:[NSURL URLWithString:@""] resultBlock:^(ALAsset *asset) {
//成功返回ALAsset
} failureBlock:^(NSError *error) {
//获取失败
}];
//通过URL地址获取相册ALAssetsGroup,该方法是异步的
[assetsLibrary groupForURL:[NSURL URLWithString:@""] resultBlock:^(ALAssetsGroup *group) {
//成功返回ALAssetsGroup
4.遍历相册
(1)遍历相册(group)
//根据指定的资源类型遍历资源相册,该方法是异步的。stop参数为指针,但赋值为YES时,停止迭代
NSArray *arrayAssetsGroup=[[NSMutableArray alloc]init];
[assetsLibrary enumerateGroupsWithTypes:ALAssetsGroupAll usingBlock:^(ALAssetsGroup *group, BOOL *stop) {
if (group) {
//group不为nil执行的操作,并将继续迭代下去
[arrayAssetsGroup addObject:group];
}else{
//group为nil时执行的操作,并停止迭代,回到主线程
[self performSelectorOnMainThread:@selector(reloadTableView) withObject:nil waitUntilDone:YES];
}
} failureBlock:^(NSError *error) {
//获取相册出错时,如该应用没有被授权访问相册时
NSLog(@"错误Error:%@",error);
}];
组类型:
enum {
ALAssetsGroupLibrary = (1 << 0), // The Library group that includes all assets.
ALAssetsGroupAlbum = (1 << 1), // All the albums synced from iTunes or created on the device.
ALAssetsGroupEvent = (1 << 2), // All the events synced from iTunes.
ALAssetsGroupFaces = (1 << 3), // All the faces albums synced from iTunes.
ALAssetsGroupSavedPhotos = (1 << 4), // The Saved Photos album.
#if __IPHONE_5_0 <= __IPHONE_OS_VERSION_MAX_ALLOWED
ALAssetsGroupPhotoStream = (1 << 5), // The PhotoStream album.
#endif
ALAssetsGroupAll = 0xFFFFFFFF, // The same as ORing together all the available group types,
};
//创建相册
//创建一个名为“test”的相册,该方法是异步的
[assetsLibrary addAssetsGroupAlbumWithName:@"test" resultBlock:^(ALAssetsGroup *group) {
//创建成功后,返回group;如果已经存在了名为“test”的相册,则返回一个nil的group
} failureBlock:^(NSError *error) {
//创建失败,可能原因有:1、用户没有授权 2、创建的资源名,时不可获得的
}];
(2)遍历相册组asset资源
//enumerateAssets都是同步的,所以我放在了一个线程中执行遍历
NSMutableArray *arrayAsset=[[NSMutableArray alloc]init];
// 获取全局调度队列,后面的标记永远是0
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
// 创建调度群组
dispatch_group_t group = dispatch_group_create();
// 向调度群组添加异步任务,并指定执行的队列
dispatch_group_async(group, queue, ^{
[self.assetsGroup enumerateAssetsUsingBlock:^(ALAsset *result, NSUInteger index, BOOL *stop) {
//result不为nil则存在资源,继续遍历;为nil则不存在资源,结束遍历
//index为该资源在资源集合中的索引
//stop为一个指针,当给其赋值YES时,停止遍历
if (result) {
[arrayAsset addObject:result];
}else{
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"回到主线程");
});
}
}];
});
//指定操作方式的,遍历。操作方式有:
//NSEnumerationConcurrent:同步的方式遍历
//NSEnumerationReverse:倒序的方式遍历
[self.assetsGroup enumerateAssetsWithOptions:NSEnumerationReverse usingBlock:^(ALAsset *result, NSUInteger index, BOOL *stop) {
//同上
}];
NSMutableIndexSet *indexes=[NSMutableIndexSet indexSetWithIndex:1];
[indexes addIndex:2];
//同上一个操作方式
//Indexes是一个索引集合,ALAssetsGroup将会取出在该索引集合中的资源
[self.assetsGroup enumerateAssetsAtIndexes:indexes options:NSEnumerationReverse usingBlock:^(ALAsset *result, NSUInteger index, BOOL *stop) {
//同上
}];
5.保存图片到系统相册
[assetsLibrary writeImageDataToSavedPhotosAlbum:imageData metadata:nil completionBlock:^(NSURL *assetURL, NSError *error) {
//保存后返回assetUrl;如果error等于nil,则保存成功
}];
[assetsLibrary writeImageToSavedPhotosAlbum:cgImageRef metadata:nil completionBlock:^(NSURL *assetURL, NSError *error) {
//保存后返回assetUrl;如果error等于nil,则保存成功
}];
[assetsLibrary writeImageToSavedPhotosAlbum:cgImageRef orientation:ALAssetOrientationDown completionBlock:^(NSURL *assetURL, NSError *error) {
//保存后返回assetUrl如果error等于nil,则保存成功
}];
//旋转方向
typedef NS_ENUM(NSInteger, ALAssetOrientation) {
ALAssetOrientationUp, //方向向上 默认
ALAssetOrientationDown, // 方向向下
ALAssetOrientationLeft, // 方向向左
ALAssetOrientationRight, // 方向向右
ALAssetOrientationUpMirrored, // 图像沿水平方向,向上翻转
ALAssetOrientationDownMirrored, // 图像沿水平方向,向下翻转
ALAssetOrientationLeftMirrored, // 图像沿垂直方向,向左翻转
ALAssetOrientationRightMirrored, // 图像沿垂直方向,向右翻转
};
//在保存视频之前,先验证一下该视频文件是否与该相册资源相匹配
if ([assetsLibrary videoAtPathIsCompatibleWithSavedPhotosAlbum:[NSURL fileURLWithPath:videoPath]]) {
//保存视频到默认相册中
[assetsLibrary writeVideoAtPathToSavedPhotosAlbum:[NSURL fileURLWithPath:videoPaht] completionBlock:^(NSURL *assetURL, NSError *error) {
//保存后返回视频资源的url;如果error等于nil,则保存成功
}]; }
保存到某个相册组:
if (self.assetsGroup.editable) {
if ([self.assetsGroup addAsset:asset]) {
NSLog(@"资源添加成功!");
}else{
NSLog(@"资源添加失败");//除了该资源集合不允许编辑导致添加失败以外,还有可能就是该资源本身不允许添加到该资源集合中
}
}
6.assetsgroup的一些属性
NSLog(@"资源集合相册的名称:%@",[assetsGroup valueForProperty:ALAssetsGroupPropertyName]);
NSLog(@"资源集合相册的类型:%@",[assetsGroup valueForProperty:ALAssetsGroupPropertyType]);
NSLog(@"资源集合相册的存储ID:%@",[assetsGroup valueForProperty:ALAssetsGroupPropertyPersistentID]);
NSLog(@"资源集合相册的存储地址URL:%@",[assetsGroup valueForProperty:ALAssetsGroupPropertyURL]);
相册组过滤:
[assetsGroup setAssetsFilter:[ALAssetsFilter allPhotos]];
[ALAssetsFilter allPhotos]; //在资源集合中获取图片
[ALAssetsFilter allVideos]; //在资源集合中获取视频
[ALAssetsFilter allAssets]; //获取所有资源
获取相册组封面:
//获取封面图片
CGImageRef imageRef=[self.assetsGroup posterImage];
UIImage *posterImage=[UIImage imageWithCGImage:imageRef];
//获取资源数量
NSInteger *assetCount=[self.assetsGroup numberOfAssets];
7.ALAsset的一些属性
//valueForProperty的属性值无效将返回:ALErrorInvalidProperty
NSLog(@"资源类别:%@",[asset valueForProperty:ALAssetPropertyType]);//有三种资源类别:ALAssetTypePhoto(图片), ALAssetTypeVideo(视频),ALAssetTypeUnknown(未知)
NSLog(@"资源拍摄地点:%@",[asset valueForProperty:ALAssetPropertyLocation]);
NSLog(@"视频持续时间:%@",[asset valueForProperty:ALAssetPropertyDuration]);
NSLog(@"资源方向:%@",[asset valueForProperty:ALAssetPropertyOrientation]);//值为枚举类型:ALAssetOrientation
NSLog(@"资源创建时间:%@",[asset valueForProperty:ALAssetPropertyDate]);
NSLog(@"资源UTI数组:%@",[asset valueForProperty:ALAssetPropertyRepresentations]);
NSLog(@"资源URL:%@",[asset valueForProperty:ALAssetPropertyAssetURL]);
NSLog(@"资源key-value集合:%@",[asset valueForProperty:ALAssetPropertyURLs]);//key:为uti;value:为url
//alsset数据
ALAssetRepresentation *
representation = [asset defaultRepresentation];
ALAssetRepresentation *
representation = [asset representationForUTI:@"public.jpeg"];
NSLog(@"资源文件的UTI:%@",[representation UTI]); //唯一标识符
NSLog(@"资源图片宽高:%@",NSStringFromCGSize([representation dimensions])); //不存在则返回CGSizeZero
NSLog(@"资源文件容量大小:%lld",[representation size]);
NSLog(@"资源文件的URL:%@",[representation url]);
NSLog(@"资源文件的旋转方向:%d",[representation orientation]); //值为上面介绍的方向枚举类型中的一个
NSLog(@"资源图片的缩放比例:%f",[representation scale]);
NSLog(@"资源文件的名称:%@",[representation filename]);
NSLog(@"资源文件的元数据:%@",[representation metadata]); //返回一个字典,如果不存在则返回nil
UIImage *resolutionImage=[UIImage imageWithCGImage:[representation fullResolutionImage]]; //资源图片高清图,不存在则返回NULL
UIImage *fullScreenImage=[UIImage imageWithCGImage:[representation fullScreenImage]]; //资源图片的全屏图,不存在则返回NULL
//缩略图
UIImage *thumbnail=[UIImage imageWithCGImage:[asset thumbnail]];
UIImage *aspectThumbnail=[UIImage imageWithCGImage:[asset aspectRatioThumbnail]];
BOOL editAble=asset.editable;
ALAsset *originalAset=asset.originalAsset;
//替换原图片
//在替换愿资源图片时,应该先要检查该资源是否可以编辑
if (asset.editable) {
[asset setImageData:imageData metadata:nil completionBlock:^(NSURL *assetURL, NSError *error) {
//如果替换成功,则返回一个资源的url,否则,assetURL为nil
}];
}
//在替换愿资源视频时,应该先要检查该资源是否可以编辑
if (asset.editable) {
[asset setVideoAtPath:videoUrl completionBlock:^(NSURL *assetURL, NSError *error) {
//如果替换成功,则返回一个资源的url,否则,assetURL为nil
}];
}
//保存一个新的图片资源,重新生成一个图片
[asset writeModifiedImageDataToSavedPhotosAlbum:imageData metadata:nil completionBlock:^(NSURL *assetURL, NSError *error) {
//成功后,返回一个新的图片URL
}];
//保存一个新的视频资源,重新生成一个视频
[asset writeModifiedVideoAtPathToSavedPhotosAlbum:videoUrl completionBlock:^(NSURL *assetURL, NSError *error) {
//成功后,返回一个新的图片URL
}];
8.获取ALAsset文件元数据
Byte *fileBuffer = (Byte*)malloc((long)representation.size); //开辟内存空间,最为缓冲区
NSUInteger bufferSize = [representation getBytes:fileBuffer fromOffset:0 length:(long)representation.size error:nil]; //把资源文件写入缓冲区
NSData *data = [NSData dataWithBytesNoCopy:fileBuffer length:bufferSize freeWhenDone:YES];//把该缓冲区的文件指向NSData
通过下面这个接口也可以获取全分辨率图片(ios9上已经废弃):
#import
NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
(id)kCFBooleanTrue, kCGImageSourceCreateThumbnailWithTransform,
(id)kCFBooleanTrue, kCGImageSourceCreateThumbnailFromImageAlways,
(id)[NSNumber numberWithFloat:200], kCGImageSourceThumbnailMaxPixelSize,
nil];
CGImageRef optionsThumbnail = [representation CGImageWithOptions:options];
UIImage *thumbnailImage = [UIImage imageWithCGImage:optionsThumbnail];