gpt4 book ai didi

ios - ALAssetLibrary 通知和 enumerateAssetsUsingBlock

转载 作者:行者123 更新时间:2023-11-29 03:00:25 25 4
gpt4 key购买 nike

我正在构建一个 iOS 应用程序,允许用户拍照并将其保存到自定义相册,该相册会使用相册中的照片填充应用程序中的 UICollectionView。我在网上找到了很多关于如何执行此操作的示例,但我无法解决相册中没有显示最新图片的顽固问题。我结束了使用通知和串行调度队列构建工作,但我认为它可以改进。

这是我保存图片然后重新填充 UICollectionView 的方式:

我构建了一个在需要枚举相册时调用的方法(viewDidLoad 以及收到 ALAssetsLibraryChangedNotification 后)。

-(void)setupCollectionView {
_assets = [@[] mutableCopy];
__block NSMutableArray *tmpAssets = [@[] mutableCopy];

// This grabs a static instance of the ALAssetsLibrary
ALAssetsLibrary *assetsLibrary = [ProfileViewController defaultAssetsLibrary];

// Enumerate through all of the ALAssets (photos) in the user’s Asset Groups (Folders)
[assetsLibrary enumerateGroupsWithTypes:ALAssetsGroupAll usingBlock:^(ALAssetsGroup *group, BOOL *stop) {
if ([[group valueForProperty:ALAssetsGroupPropertyName] isEqualToString:albumName]) {
// Make sure we have the group... (this may be redundant)
if (group == nil){
return;
}

// I read in some SO posts that setting the filter might help, but I don't think it does
NSLog(@"Refresh pictures - %d",[group numberOfAssets]);
[group setAssetsFilter:[ALAssetsFilter allPhotos]];//this will cause group to reload
if (group!=nil) {
[group enumerateAssetsUsingBlock:^(ALAsset *result, NSUInteger index, BOOL *stop) {
if(result){
[tmpAssets addObject:result];
}else{
*stop = YES;
}
}];
}

self.assets = tmpAssets;

// Reload the UICollectionView
dispatch_async(dispatch_get_main_queue(), ^{
[self.collectionView reloadData];
[self.collectionView.collectionViewLayout invalidateLayout];
});
}
} failureBlock:^(NSError *error) {
NSLog(@"Error loading images %@", error);
}];
}

最初,这似乎工作得很好,但有时,在将图像写入自定义相册后调用此方法时,刚刚拍摄的照片不会出现在 Collection View 中。照片将保存到库中(它显示在照片应用程序中),退出并重新运行应用程序后,照片将出现,但枚举不会包含最新的照片。

正如一些关于此事的 Stack Overflow 帖子所建议的,我尝试通过监听 ALAssetsLibraryChangedNotification 来实现 ALAssets 的通知,但我遇到了一些问题。这是我收到通知后正在做的事情:

- (void) handleAssetChangedNotifiation:(NSNotification *)notification {
NSDictionary *userInfo = notification.userInfo;
NSSet *updateAssets = userInfo[ALAssetLibraryUpdatedAssetsKey];
if (updateAssets.count>0) {
dispatch_sync(photoLoadQueue, ^{
[self setupCollectionView];
});
}
}

这对我来说似乎很好。我正在检查 ALAssetLibraryUpdatedAssetsKey 中是否有任何数据,然后将其扔到调度队列中,一旦我发现我收到了多个保存单张照片的通知,我就开始使用该队列。这是我将照片写入自定义库后收到的通知:

Received notification: NSConcreteNotification 0x15ed4af0 {name = ALAssetsLibraryChangedNotification; object = <ALAssetsLibrary: 0x15db9e80>; userInfo = {
ALAssetLibraryUpdatedAssetGroupsKey = "{(\n assets-library://group/?id=43E80EF8-EA91-4C71-AFD2-EBDCB53A1D53\n)}";
ALAssetLibraryUpdatedAssetsKey = "{(\n assets-library://asset/asset.JPG?id=63E43AF3-3729-43E9-806C-BE463116FDA2&ext=JPG,\n assets-library://asset/asset.JPG?id=FA2ED24E-DF0F-49A3-85B8-9C181E4077A4&ext=JPG,\n assets-library://asset/asset.JPG?id=A0B66E2E-6EA1-462C-AD93-DB3087BA65D8&ext=JPG\n)}";}}

Received notification: NSConcreteNotification 0x15d538c0 {name = ALAssetsLibraryChangedNotification; object = <ALAssetsLibrary: 0x15db9e80>; userInfo = {
ALAssetLibraryUpdatedAssetsKey = "{(\n assets-library://asset/asset.JPG?id=FBDD2086-EC76-473F-A23E-4F4200C0A6DF&ext=JPG\n)}";}}

Received notification: NSConcreteNotification 0x15dc9230 {name = ALAssetsLibraryChangedNotification; object = <ALAssetsLibrary: 0x15db9e80>; userInfo = {}}

Received notification: NSConcreteNotification 0x15df5b40 {name = ALAssetsLibraryChangedNotification; object = <ALAssetsLibrary: 0x15db9e80>; userInfo = {}}

Received notification: NSConcreteNotification 0x15d6a050 {name = ALAssetsLibraryChangedNotification; object = <ALAssetsLibrary: 0x15db9e80>; userInfo = {}}

Received notification: NSConcreteNotification 0x15d379e0 {name = ALAssetsLibraryChangedNotification; object = <ALAssetsLibrary: 0x15db9e80>; userInfo = {
ALAssetLibraryUpdatedAssetGroupsKey = "{(\n assets-library://group/?id=1E76AFA7-89B4-4277-A175-D7C8E62E49D0&filter=1,\n assets-library://group/?id=1E76AFA7-89B4-4277-A175-D7C8E62E49D0\n)}";
ALAssetLibraryUpdatedAssetsKey = "{(\n assets-library://asset/asset.JPG?id=FBDD2086-EC76-473F-A23E-4F4200C0A6DF&ext=JPG\n)}";

Received notification: NSConcreteNotification 0x15df7bf0 {name = ALAssetsLibraryChangedNotification; object = <ALAssetsLibrary: 0x15db9e80>; userInfo = {
ALAssetLibraryUpdatedAssetGroupsKey = "{(\n assets-library://group/?id=8E390051-E107-42BC-AE55-24BA35966642\n)}";}}

Received notification: NSConcreteNotification 0x15d40360 {name = ALAssetsLibraryChangedNotification; object = <ALAssetsLibrary: 0x15db9e80>; userInfo = {
ALAssetLibraryUpdatedAssetsKey = "{(\n assets-library://asset/asset.JPG?id=5A45779A-C3C1-4545-9BD6-88F094FFA5B9&ext=JPG\n)}";}}

为什么我会收到这么多通知?我没有找到一种方法来查找一条特定消息,该消息会在图像准备好后告诉我,因此我使用该调度队列来连续触发枚举。有没有人对此有任何经验或解决方案?我的作品,但我确实做了比我应该做的更多的工作。

为了完整起见,这是我保存图像的方法(我可能不应该像我一样嵌套这些 block ,但我这样做是为了尝试修复未检测到的添加图像):

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
UIImage *originalImage, *editedImage, *imageToSave;
editedImage = (UIImage *) [info objectForKey:UIImagePickerControllerEditedImage];
originalImage = (UIImage *) [info objectForKey:UIImagePickerControllerOriginalImage];
if (editedImage) {
imageToSave = editedImage;
}else {
imageToSave = originalImage;
}

// Get group/asset library/album
__block ALAssetsGroup* groupToAddTo;
ALAssetsLibrary *assetsLibrary = [ProfileViewController defaultAssetsLibrary];
[[NSNotificationCenter defaultCenter] removeObserver:self name:ALAssetsLibraryChangedNotification object:nil];

[assetsLibrary enumerateGroupsWithTypes:ALAssetsGroupAll usingBlock:^(ALAssetsGroup *group, BOOL *stop) {
if ([[group valueForProperty:ALAssetsGroupPropertyName] isEqualToString:albumName]) {
NSLog(@"found album %@", albumName);
groupToAddTo = group;

// save to album
CGImageRef img = [imageToSave CGImage];

// There's some orientation stuff here I pulled out for brevity's sake

[assetsLibrary writeImageToSavedPhotosAlbum:img orientation: alOrientation completionBlock:^(NSURL* assetURL, NSError* error) {
if (error.code == 0) {
[assetsLibrary assetForURL:assetURL resultBlock:^(ALAsset *asset) {
// assign the photo to the album
if ([groupToAddTo valueForProperty:ALAssetsGroupPropertyURL] == nil){
NSLog(@"group properties are nil!");
}else {
if([groupToAddTo addAsset:asset]){
// If the asset writes to the library, listen for the notification
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleAssetChangedNotifiation:) name:ALAssetsLibraryChangedNotification object:nil];
}else {
NSLog(@"Image Not Added!");
}
}
}
failureBlock:^(NSError* error) {
NSLog(@"failed to retrieve image asset:\nError: %@ ", [error localizedDescription]);
}];
}else {
NSLog(@"saved image failed.\nerror code %i\n%@", error.code, [error localizedDescription]);
}
}];
}}
failureBlock:^(NSError* error) {
NSLog(@"failed to enumerate albums:\nError: %@", [error localizedDescription]);}];

[picker dismissViewControllerAnimated:YES completion:NULL];
}

最佳答案

需要注意的是,与 ALAssetsLibrary 关联的 block 是异步。因此,这样的代码不起作用:

        if (group!=nil) {
[group enumerateAssetsUsingBlock:^(ALAsset *result, NSUInteger index, BOOL *stop) {
if(result){
[tmpAssets addObject:result];
}else{
*stop = YES;
}
}];
}
self.assets = tmpAssets;

“最后”行 self.assets = tmpAssets 在 block 之前运行 - 因此 tmpAssets 永远没有机会成为设置正确。

对于与 ALAssetsLibrary 调用关联的所有 block ,同样的事情也是如此。

一旦你掌握了这一点,你就可以重构你的代码,以便一切都按正确的顺序发生。事实上,事实证明,这就是额外通过枚举 block 的目的。正如我在书中所写:

I was initially mystified by this curious block enumeration behavior, but one day the reason for it came to me in a flash: these blocks are all called asynchronously (on the main thread), meaning that the rest of your code has already finished running, so you're given an extra pass through the block as your first opportunity to do something with all the data you've presumably gathered in the previous passes.

所以你看,你希望你的代码结构更像这样:

        if (group!=nil) {
[group enumerateAssetsUsingBlock:^(ALAsset *result, NSUInteger index, BOOL *stop) {
if(result){
[tmpAssets addObject:result];
}else{
self.assets = tmpAssets; // <--- !!!!
// and now proceed to whatever the _next_ step is...!
}
}];
}

所以,你看,你完全走错了路。摆脱所有您的通知并根据这些新知识完全重构您的所有代码。一旦您理解了这个简单但缺乏记录的关于它如何工作的事实,ALAssetsLibrary 就完全连贯了。​​

关于ios - ALAssetLibrary 通知和 enumerateAssetsUsingBlock,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23378377/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com