iOS 获取系统相册全部照片以及照片信息
2015-06-03 12:22
776 查看
感谢:smile筱提供了参考代码传输门。
本文是在他的代码的基础上的进一步修改。
写下本博客主要是为了自己备份知识。方便查找。转载请注明出处!
具体实现:
优化一:
优化二(使用block回调):
+ (void)SystemPhotoAlbumPhotoSuccess:(void(^)(NSArray *photoArray))success progress:(void(^)(int currentCount,int totalCount))progress fail:(void(^)(NSString *error))fail{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
__block int photoCount = 0;
__block NSMutableArray *phArray = [NSMutableArray array];
ALAssetsLibraryAccessFailureBlock failureblock = ^(NSError *myerror){
dispatch_async(dispatch_get_main_queue(), ^{
if (fail) {
fail([myerror localizedDescription]);
}
NSLog(@"相册访问失败 =%@", [myerror localizedDescription]);
if ([myerror.localizedDescription rangeOfString:@"Global denied access"].location!=NSNotFound) {
NSLog(@"无法访问相册.请在'设置->定位服务'设置为打开状态.");
}else{
NSLog(@"相册访问失败.");
}
});
};
ALAssetsGroupEnumerationResultsBlock groupEnumerAtion = ^(ALAsset *result,NSUInteger index, BOOL *stop){
if (result!=NULL) {
if ([[result valueForProperty:ALAssetPropertyType]isEqualToString:ALAssetTypePhoto]) {
NSString *photoDefaultPath=[NSString stringWithFormat:@"%@",result.defaultRepresentation.url];
NSString *photoThumPath=[NSString stringWithFormat:@"%@",result.defaultRepresentation.url];
NSString *photoName=[NSString stringWithFormat:@"%@",result.defaultRepresentation.filename];
NSDictionary *photoMetaData = result.defaultRepresentation.metadata;
NSDictionary *photoGPS = [photoMetaData objectForKey:@"{GPS}"];
if (photoGPS == nil) {
photoGPS = @{@"Latitude":@"0.0",@"Longitude":@"0.0"};
}
NSString *photoDateTime;
if ([[photoMetaData objectForKey:@"{TIFF}"] objectForKey:@"DateTime"] == nil) {
photoDateTime = @"0";
}else{
photoDateTime = [[photoMetaData objectForKey:@"{TIFF}"] objectForKey:@"DateTime"];
}
//图片的url
/*result.defaultRepresentation.fullScreenImage//图片的大图
result.thumbnail //图片的缩略图小图
// NSRange range1=[urlstr rangeOfString:@"id="];
// NSString *resultName=[urlstr substringFromIndex:range1.location+3];
// resultName=[resultName stringByReplacingOccurrencesOfString:@"&ext=" withString:@"."];//格式demo:123456.png
*/
NSDictionary *photoDic = @{@"photoDefaultPath":photoDefaultPath,@"photoThumPath":photoThumPath,@"photoName":photoName,@"photoGPS":photoGPS,@"photoDateTime":photoDateTime};
// NSLog(@"photoDic:%@",photoDic);
[phArray addObject:photoDic];
// NSLog(@"加载全部照片共%d张中的第%d张",photoCount,index + 1);
dispatch_async(dispatch_get_main_queue(), ^{
if (progress) {
progress(index +1 , photoCount);
}
});
if (photoCount == index + 1) {
// NSLog(@"全部加载完毕");
dispatch_async(dispatch_get_main_queue(), ^{
if (success) {
success(phArray);
}
});
}
}
}
};
ALAssetsLibraryGroupsEnumerationResultsBlock
libraryGroupsEnumeration = ^(ALAssetsGroup* group,BOOL* stop){
if (group!=nil) {
NSString *g=[NSString stringWithFormat:@"%@",group];//获取相簿的组
// NSLog(@"gg:%@",g);//gg:ALAssetsGroup - Name:Camera Roll, Type:Saved Photos, Assets count:71
NSString *g1=[g substringFromIndex:16 ] ;
NSArray *arr=[NSArray arrayWithArray:[g1 componentsSeparatedByString:@","]];
NSString *g2=[[arr o
a0b1
bjectAtIndex:0]substringFromIndex:5];
if ([g2 isEqualToString:@"Camera Roll"]) {
g2=@"相机胶卷";
}
// NSString *groupName=g2;//组的name
photoCount = group.numberOfAssets;
[group enumerateAssetsUsingBlock:groupEnumerAtion];
}else{
}
};
ALAssetsLibrary* library = [[ALAssetsLibrary alloc] init];
[library enumerateGroupsWithTypes:ALAssetsGroupAll
usingBlock:libraryGroupsEnumeration
failureBlock:failureblock];
});
}
下面是调用实例(ToolsManager是我的一个工具类,我将此方法写进工具类作为类方法调用):
[ToolsManager SystemPhotoAlbumPhotoSuccess:^(NSArray *photoArray) {
NSLog(@"photoArray.count:%d",photoArray.count);
} progress:^(int currentCount, int totalCount) {
CGFloat percent = (CGFloat)currentCount/(CGFloat)totalCount;
_photoAlbumBtn.text = [NSString stringWithFormat:@"载入照片中(%d%%)...",(int)(percent * 100)];
_photoAlbumBtn.progress = percent;
} fail:^(NSString *error) {
UIAlertView *av;
if ([error rangeOfString:@"Global denied access"].location!=NSNotFound) {
av = [[UIAlertView alloc] initWithTitle:@"错误"
message:@"无法访问相册.请在'设置->定位服务'设置为打开状态."
delegate:self
cancelButtonTitle:@"好的"
otherButtonTitles:nil, nil];
}else{
av = [[UIAlertView alloc] initWithTitle:@"错误"
message:@"相册访问失败." delegate:self
cancelButtonTitle:@"好的"
otherButtonTitles:nil, nil];
}
[av show];
}];
上面是获取照片URL的。
根据照片URL可以用一下代码来反向获取到UIImage
本文是在他的代码的基础上的进一步修改。
写下本博客主要是为了自己备份知识。方便查找。转载请注明出处!
具体实现:
#import <AssetsLibrary/AssetsLibrary.h>
优化一:
-(void)getImgs{ dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ __block int photoCount = 0; ALAssetsLibraryAccessFailureBlock failureblock = ^(NSError *myerror){ NSLog(@"相册访问失败 =%@", [myerror localizedDescription]); if ([myerror.localizedDescription rangeOfString:@"Global denied access"].location!=NSNotFound) { NSLog(@"无法访问相册.请在'设置->定位服务'设置为打开状态."); }else{ NSLog(@"相册访问失败."); } }; ALAssetsGroupEnumerationResultsBlock groupEnumerAtion = ^(ALAsset *result,NSUInteger index, BOOL *stop){ if (result!=NULL) { if ([[result valueForProperty:ALAssetPropertyType]isEqualToString:ALAssetTypePhoto]) { NSString *photoDefaultPath=[NSString stringWithFormat:@"%@",result.defaultRepresentation.url]; NSString *photoThumPath=[NSString stringWithFormat:@"%@",result.defaultRepresentation.url]; NSString *photoName=[NSString stringWithFormat:@"%@",result.defaultRepresentation.filename]; NSDictionary *photoMetaData = result.defaultRepresentation.metadata; NSDictionary *photoGPS = [photoMetaData objectForKey:@"{GPS}"]; if (photoGPS == nil) { photoGPS = @{@"Latitude":@"0.0",@"Longitude":@"0.0"}; } NSString *photoDateTime; if ([[photoMetaData objectForKey:@"{TIFF}"] objectForKey:@"DateTime"] == nil) { photoDateTime = @"0"; }else{ photoDateTime = [[photoMetaData objectForKey:@"{TIFF}"] objectForKey:@"DateTime"]; } //图片的url /*result.defaultRepresentation.fullScreenImage//图片的大图 result.thumbnail //图片的缩略图小图 // NSRange range1=[urlstr rangeOfString:@"id="]; // NSString *resultName=[urlstr substringFromIndex:range1.location+3]; // resultName=[resultName stringByReplacingOccurrencesOfString:@"&ext=" withString:@"."];//格式demo:123456.png */ NSDictionary *photoDic = @{@"photoDefaultPath":photoDefaultPath,@"photoThumPath":photoThumPath,@"photoName":photoName,@"photoGPS":photoGPS,@"photoDateTime":photoDateTime}; NSLog(@"photoDic:%@",photoDic); [_systemPhotoArray addObject:photoDic]; NSLog(@"加载全部照片共%d张中的第%d张",photoCount,index + 1); if (photoCount == index + 1) { NSLog(@"全部加载完毕"); } } } }; ALAssetsLibraryGroupsEnumerationResultsBlock libraryGroupsEnumeration = ^(ALAssetsGroup* group,BOOL* stop){ if (group!=nil) { NSString *g=[NSString stringWithFormat:@"%@",group];//获取相簿的组 NSLog(@"gg:%@",g);//gg:ALAssetsGroup - Name:Camera Roll, Type:Saved Photos, Assets count:71 NSString *g1=[g substringFromIndex:16 ] ; NSArray *arr=[NSArray arrayWithArray:[g1 componentsSeparatedByString:@","]]; NSString *g2=[[arr objectAtIndex:0]substringFromIndex:5]; if ([g2 isEqualToString:@"Camera Roll"]) { g2=@"相机胶卷"; } // NSString *groupName=g2;//组的name photoCount = group.numberOfAssets; [group enumerateAssetsUsingBlock:groupEnumerAtion]; }else{ } }; ALAssetsLibrary* library = [[ALAssetsLibrary alloc] init]; [library enumerateGroupsWithTypes:ALAssetsGroupAll usingBlock:libraryGroupsEnumeration failureBlock:failureblock]; }); }
优化二(使用block回调):
+ (void)SystemPhotoAlbumPhotoSuccess:(void(^)(NSArray *photoArray))success progress:(void(^)(int currentCount,int totalCount))progress fail:(void(^)(NSString *error))fail{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
__block int photoCount = 0;
__block NSMutableArray *phArray = [NSMutableArray array];
ALAssetsLibraryAccessFailureBlock failureblock = ^(NSError *myerror){
dispatch_async(dispatch_get_main_queue(), ^{
if (fail) {
fail([myerror localizedDescription]);
}
NSLog(@"相册访问失败 =%@", [myerror localizedDescription]);
if ([myerror.localizedDescription rangeOfString:@"Global denied access"].location!=NSNotFound) {
NSLog(@"无法访问相册.请在'设置->定位服务'设置为打开状态.");
}else{
NSLog(@"相册访问失败.");
}
});
};
ALAssetsGroupEnumerationResultsBlock groupEnumerAtion = ^(ALAsset *result,NSUInteger index, BOOL *stop){
if (result!=NULL) {
if ([[result valueForProperty:ALAssetPropertyType]isEqualToString:ALAssetTypePhoto]) {
NSString *photoDefaultPath=[NSString stringWithFormat:@"%@",result.defaultRepresentation.url];
NSString *photoThumPath=[NSString stringWithFormat:@"%@",result.defaultRepresentation.url];
NSString *photoName=[NSString stringWithFormat:@"%@",result.defaultRepresentation.filename];
NSDictionary *photoMetaData = result.defaultRepresentation.metadata;
NSDictionary *photoGPS = [photoMetaData objectForKey:@"{GPS}"];
if (photoGPS == nil) {
photoGPS = @{@"Latitude":@"0.0",@"Longitude":@"0.0"};
}
NSString *photoDateTime;
if ([[photoMetaData objectForKey:@"{TIFF}"] objectForKey:@"DateTime"] == nil) {
photoDateTime = @"0";
}else{
photoDateTime = [[photoMetaData objectForKey:@"{TIFF}"] objectForKey:@"DateTime"];
}
//图片的url
/*result.defaultRepresentation.fullScreenImage//图片的大图
result.thumbnail //图片的缩略图小图
// NSRange range1=[urlstr rangeOfString:@"id="];
// NSString *resultName=[urlstr substringFromIndex:range1.location+3];
// resultName=[resultName stringByReplacingOccurrencesOfString:@"&ext=" withString:@"."];//格式demo:123456.png
*/
NSDictionary *photoDic = @{@"photoDefaultPath":photoDefaultPath,@"photoThumPath":photoThumPath,@"photoName":photoName,@"photoGPS":photoGPS,@"photoDateTime":photoDateTime};
// NSLog(@"photoDic:%@",photoDic);
[phArray addObject:photoDic];
// NSLog(@"加载全部照片共%d张中的第%d张",photoCount,index + 1);
dispatch_async(dispatch_get_main_queue(), ^{
if (progress) {
progress(index +1 , photoCount);
}
});
if (photoCount == index + 1) {
// NSLog(@"全部加载完毕");
dispatch_async(dispatch_get_main_queue(), ^{
if (success) {
success(phArray);
}
});
}
}
}
};
ALAssetsLibraryGroupsEnumerationResultsBlock
libraryGroupsEnumeration = ^(ALAssetsGroup* group,BOOL* stop){
if (group!=nil) {
NSString *g=[NSString stringWithFormat:@"%@",group];//获取相簿的组
// NSLog(@"gg:%@",g);//gg:ALAssetsGroup - Name:Camera Roll, Type:Saved Photos, Assets count:71
NSString *g1=[g substringFromIndex:16 ] ;
NSArray *arr=[NSArray arrayWithArray:[g1 componentsSeparatedByString:@","]];
NSString *g2=[[arr o
a0b1
bjectAtIndex:0]substringFromIndex:5];
if ([g2 isEqualToString:@"Camera Roll"]) {
g2=@"相机胶卷";
}
// NSString *groupName=g2;//组的name
photoCount = group.numberOfAssets;
[group enumerateAssetsUsingBlock:groupEnumerAtion];
}else{
}
};
ALAssetsLibrary* library = [[ALAssetsLibrary alloc] init];
[library enumerateGroupsWithTypes:ALAssetsGroupAll
usingBlock:libraryGroupsEnumeration
failureBlock:failureblock];
});
}
下面是调用实例(ToolsManager是我的一个工具类,我将此方法写进工具类作为类方法调用):
[ToolsManager SystemPhotoAlbumPhotoSuccess:^(NSArray *photoArray) {
NSLog(@"photoArray.count:%d",photoArray.count);
} progress:^(int currentCount, int totalCount) {
CGFloat percent = (CGFloat)currentCount/(CGFloat)totalCount;
_photoAlbumBtn.text = [NSString stringWithFormat:@"载入照片中(%d%%)...",(int)(percent * 100)];
_photoAlbumBtn.progress = percent;
} fail:^(NSString *error) {
UIAlertView *av;
if ([error rangeOfString:@"Global denied access"].location!=NSNotFound) {
av = [[UIAlertView alloc] initWithTitle:@"错误"
message:@"无法访问相册.请在'设置->定位服务'设置为打开状态."
delegate:self
cancelButtonTitle:@"好的"
otherButtonTitles:nil, nil];
}else{
av = [[UIAlertView alloc] initWithTitle:@"错误"
message:@"相册访问失败." delegate:self
cancelButtonTitle:@"好的"
otherButtonTitles:nil, nil];
}
[av show];
}];
上面是获取照片URL的。
根据照片URL可以用一下代码来反向获取到UIImage
//------------------------根据图片的url反取图片----- ALAssetsLibrary *assetLibrary=[[ALAssetsLibraryalloc] init]; NSURL *url=[NSURLURLWithString:urlStr]; [assetLibrary assetForURL:url resultBlock:^(ALAsset *asset) { UIImage *image=[UIImage imageWithCGImage:asset.thumbnail]; cellImageView.image=image; }failureBlock:^(NSError *error) { NSLog(@"error=%@",error); } ]; //---------------------
相关文章推荐
- 峰回路转,Firefox 浏览器即将重返 iOS 平台
- 峰回路转,Firefox 浏览器即将重返 iOS 平台
- 不可修补的 iOS 漏洞可能导致 iPhone 4s 到 iPhone X 永久越狱
- iOS 12.4 系统遭黑客破解,漏洞危及数百万用户
- 每日安全资讯:NSO,一家专业入侵 iPhone 的神秘公司
- [转][源代码]Comex公布JailbreakMe 3.0源代码
- js判断客户端是iOS还是Android等移动终端的方法
- IOS开发环境windows化攻略
- .net平台推送ios消息的实现方法
- 探讨Android与iOS,我们将何去何从?
- Android、iOS和Windows Phone中的推送技术详解
- IOS 改变键盘颜色代码
- Android和IOS的浏览器中检测是否安装某个客户端的方法
- javascript实现阻止iOS APP中的链接打开Safari浏览器
- iOS开发之路--微博OAuth授权_取得用户授权的accessToken
- ios通过按钮点击异步加载图片
- ios中图像进行压缩方法汇总
- IOS检测指定路径的文件是否存在
- iOS、Mac OS X系统中编程实现汉字转拼音的方法(超级简单)