我正在尝试获取photos.app中的所有图像,并将它们显示在UICollectionView中.我有这个代码检索图像:
ALAssetsLibrary *al = [ViewController defaultAssetsLibrary];
ALAssetsGroupEnumerationResultsBlock groupEnumerAtion = ^(ALAsset *result,NSUInteger index,BOOL *stop){
if (result!=NULL) {
if ([[result valueForProperty:ALAssetPropertyType] isEqualToString:ALAssetTypePhoto]) {
[imagesGotFromUserLibrary addobject:result];
}
}
};
ALAssetsLibraryGroupsEnumerationResultsBlock
libraryGroupsEnumeration = ^(ALAssetsGrouP* group,BOOL* stop){
[group setAssetsFilter:[ALAssetsFilter allPhotos]];
if (group!=nil)
{
[group enumerateAssetsUsingBlock:groupEnumerAtion];
}
else
{
dispatch_async(dispatch_get_global_queue(0,0),^{
galleryCollectionViewController *otherController = [[galleryCollectionViewController alloc] init];
[otherController receiveImagesWithMutableArray:imagesGotFromUserLibrary];
});
}
};
al = [[ALAssetsLibrary alloc] init];
[al enumerateGroupsWithTypes:ALAssetsGroupSavedPhotos
usingBlock:libraryGroupsEnumeration
failureBlock:^(NSError *error){
NSLog(@"ERROR: %@",error);
}];
这是在viewDidLoad然后:
+ (ALAssetsLibrary *)defaultAssetsLibrary {
static dispatch_once_t pred = 0;
static ALAssetsLibrary *library = nil;
dispatch_once(&pred,^{
library = [[ALAssetsLibrary alloc] init];
});
return library;
}
这段代码是将数组发送到另一个控制器,将控制器设置为UICollectionView.问题是,我收到错误“无效尝试访问其拥有的ALAssetsLibrary的生命周期”,如果我尝试使用NSLog我的数组,结果就像“ALAsset – Type:UnkNown”,URL:(null)“.
我抬头看了互联网,找到了一个解决方案.我应该添加这行代码,但它不起作用.代码是:
+ (ALAssetsLibrary *)defaultAssetsLibrary {
static dispatch_once_t pred = 0;
static ALAssetsLibrary *library = nil;
dispatch_once(&pred,^{
library = [[ALAssetsLibrary alloc] init];
});
return library;
}
任何人都可以帮助我获取正确的图片网址来显示?
解决方法
解决方案是始终使用相同的库来对所有类的资产进行所有访问.上面显示的单例解决方案是好的 – 只要所有的类都调用defaultAssetsLibrary,并且没有人分配/ init自己的ALAssetLibrary.