我正在尝试获取 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, URLs:(null)”。
我在互联网上查找并找到了解决方案。我应该添加这行代码,但它不起作用。代码是:
+ (ALAssetsLibrary *)defaultAssetsLibrary {
static dispatch_once_t pred = 0;
static ALAssetsLibrary *library = nil;
dispatch_once(&pred, ^{
library = [[ALAssetsLibrary alloc] init];
});
return library;
}
任何人都可以帮助我获得正确的图像 URL 以显示?