我想访问并将我的iPhone相册中的一个相册中的所有照片复制到应用程序启动时自动应用程序的文档文件夹中。
关于使用UIImagePicker,这里有很多问题/答案。我知道我可以使用图像选择器并让用户选择照片但我真的很喜欢它,如果我可以在没有用户选择照片的情况下完成它。
我使用以下问题/答案来帮助解决以下代码:How to retrieve the most recent photo from Camera Roll on iOS?
我能够在我的文档文件夹中成功保存一个图像,但无法弄清楚如何一次保存多个图像。
ALAssetsLibrary *assetsLibrary = [[ALAssetsLibrary alloc] init];
[assetsLibrary enumerateGroupsWithTypes: ALAssetsGroupAlbum //ALAssetsGroupAlbum before I CHANGED it
usingBlock:^(ALAssetsGroup *group, BOOL *stop) { //
if (nil != group) {
// be sure to filter the group so you only get photos
[group setAssetsFilter:[ALAssetsFilter allPhotos]];
[group enumerateAssetsAtIndexes:[NSIndexSet indexSetWithIndex: group.numberOfAssets - 1 ]// -1
options:0
usingBlock:^(ALAsset *result, NSUInteger index, BOOL *stop) {
if (nil != result)
{
ALAssetRepresentation *repr = [result defaultRepresentation];
// this is the most recent saved photo
UIImage *img = [UIImage imageWithCGImage:[repr fullResolutionImage]];
// we only need the first (most recent) photo -- stop the enumeration
// *stop = YES;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
int num = 1;
NSString* path = [documentsDirectory stringByAppendingPathComponent: [NSString stringWithFormat:@"%@-%d.png",@"boxOneImage", num]];
num++;
NSData* data = UIImagePNGRepresentation(img);
[data writeToFile:path atomically: YES];
}
}];
}
*stop = NO;
} failureBlock:^(NSError *error) {
NSLog(@"error: %@", error);
}];
更新:我能够解决这个问题并使用以下代码将图像从相册卷而不是相机胶卷加载到我的应用文档文件夹:
__block int num = 1;
ALAssetsLibrary *assetsLibrary = [[ALAssetsLibrary alloc] init];
[assetsLibrary enumerateGroupsWithTypes:ALAssetsGroupAlbum usingBlock:^(ALAssetsGroup *group, BOOL *stop)
{
if (nil != group)
{
[group setAssetsFilter:[ALAssetsFilter allPhotos]];
[group enumerateAssetsUsingBlock:^(ALAsset *result, NSUInteger index, BOOL *stop){
if (nil != result)
{
ALAssetRepresentation *repr = [result defaultRepresentation];
// this is the most recent saved photo
UIImage *img = [UIImage imageWithCGImage:[repr fullResolutionImage]];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString* path = [documentsDirectory stringByAppendingPathComponent: [NSString stringWithFormat:@"%@-%d.png",@"boxOneImage", num]];
num++;
NSData* data = UIImagePNGRepresentation(img);
[data writeToFile:path atomically: YES];
}
}];
}
*stop = NO;
} failureBlock:^(NSError *error)
{
NSLog(@"error: %@", error);
}];
如果有人拥有或知道更好的方法,请分享。我很想看到它并从中学习。感谢!!!
答案 0 :(得分:0)
我认为您现有的方法本身只会进行一些小改动。
删除块中的int num = 1;
并在块外添加__block int num = 1;
,可能在assetsLibrary
初始化之前。
或者更好的解决方案,完全删除变量num
,使用传递给块的index+1
!