iOS 获取系统相册全部照片以及照片信息

来源:互联网 发布:淘宝上真正的原单店 编辑:程序博客网 时间:2024/04/29 09:37

感谢:smile筱提供了参考代码传输门。

本文是在他的代码的基础上的进一步修改。

写下本博客主要是为了自己备份知识。方便查找。转载请注明出处!

具体实现:

#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 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];    });}



下面是调用实例(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);            }             ];//---------------------


0 0