图像选择器 iOS

Image picker iOS

在我的图像选择器中,我使用了以下代码

- (void)imageAtIndex:(NSInteger)index completionHandler:(void(^)(UIImage *image))completionHandler
{
  NSDictionary *image = self.images[index];
  [self.library assetForURL:image[@"URL"] resultBlock:^(ALAsset *asset) {
    ALAssetRepresentation *representation = [asset defaultRepresentation];
    UIImage *returnImage = [UIImage imageWithCGImage:[representation fullResolutionImage]
                                               scale:[representation scale]
                                         orientation:(int)[representation orientation]];
    completionHandler(returnImage);
} failureBlock:^(NSError *error) {
    NSLog(@"Error loading asset");
}];
}

我select图片使用下面的代码

[self.cameraRoll imageAtIndex:indexPath.row-1 completionHandler:^(UIImage *image) {
        myImage=image;
    }];

当我 select 第一次给出值 "nil" 当我第二次 select 相同的图像时,它正确地选择了图像。

如何解决这个问题。

我希望这对某人有所帮助,所以张贴答案。我们必须等到库加载完毕,因为我正在使用 while 循环......它工作得很好

- (void)imageAtIndex:(NSInteger)index completionHandler:(void(^)(UIImage *image1))completionHandler
{
__block BOOL isFinished = NO;

NSDictionary *image = self.images[index];


[self.library assetForURL:image[@"URL"] resultBlock:^(ALAsset *asset) {


    ALAssetRepresentation *representation = [asset defaultRepresentation];
    UIImage *returnImage = [UIImage imageWithCGImage:[representation fullResolutionImage]
                                               scale:[representation scale]
                                         orientation:(int)[representation orientation]];

   isFinished = YES;

    completionHandler(returnImage);
} failureBlock:^(NSError *error) {
    NSLog(@"Error: Cannot load asset - %@", [error localizedDescription]);
    isFinished = YES;
}];
while (!isFinished) {
    [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.01f]];
}
}