gpt4 book ai didi

ios - ALAssetsLibrary,等到assetForURL 完成

转载 作者:行者123 更新时间:2023-12-01 19:01:35 27 4
gpt4 key购买 nike

我有一个包含与 assetslibrary 中的图像相对应的 imageurls 的数组,我需要在执行某个任务之前获取所有这些图像。这样做的最佳方法是什么?我应该使用 NSNotificationCenter还是最好使用 block ,如果是这样,有什么例子吗?

这是我的代码:

- (IBAction)buttonClicked:(id)sender {

NSMutableArray* images = [NSMutableArray array];
//Need to loop through the takenImagesURLArray
for (NSURL *imageURL in takenImagesURLArray) {
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
[library assetForURL:imageURL
resultBlock:^(ALAsset *asset) {
if (asset) {
NSLog(@"HAS ASSET: %@", asset);
UIImage *image = [UIImage imageWithCGImage:[[asset defaultRepresentation] fullResolutionImage]];
[images addObject:image];
} else {
NSLog(@"Something went wrong");
}
}
failureBlock:^(NSError *error) {
NSLog(@"Something went wrong, %@", error);
}];
}
//This will of course be called before images is ready
[self doCertainTaskWith: images];
}

最佳答案

您可以为此使用 Grand Central Dispatch。

但首先,移动 ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];在 for 循环之外,因为它可以被重用。

现在是真正的代码。它看起来像这样:

dispatch_group_t dgroup = dispatch_group_create(); //0

ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];

for (NSURL *imageURL in urls) {

dispatch_group_enter(dgroup); // 1

[library assetForURL:imageURL resultBlock:^(ALAsset *asset) {
if (asset) {
NSLog(@"HAS ASSET: %@", asset);
UIImage *image = [UIImage imageWithCGImage:[[asset defaultRepresentation] fullResolutionImage]];
[images addObject:image];

dispatch_group_leave(dgroup); //2

} else {
NSLog(@"Something went wrong");
dispatch_group_leave(dgroup);
}
} failureBlock:^(NSError *error) {
NSLog(@"Something went wrong, %@", error);
dispatch_group_leave(dgroup);
}];

}

dispatch_group_notify(dgroup, dispatch_get_main_queue(), ^{ //3

NSLog(@"Do something with %d images", [images count]);

});

代码解释(遵循代码中的注释)
  • 我们创建了一个小组,帮助我们实现我们想要的。把它想象成一个简单的列表。
  • 我们将每个项目输入到组中。将其视为增加 retain支持一个对象,在这种情况下,我们的组。
  • 完成后,我们告诉它离开该组。把它想象成调用 release在一个物体上。
  • 当组上的计数回到 0 时,所有任务都已完成。无论您需要对图像做什么,都可以在这里完成。
  • 关于ios - ALAssetsLibrary,等到assetForURL 完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22475947/

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