Получить последнюю сохраненную фотографию в фотоальбоме

Я использую AVFoundation framework для фотографирования и сохраняю его в фотоальбом:

- (void)captureStillImage
{  
    AVCaptureConnection *videoConnection = nil;
    for (AVCaptureConnection *connection in [[self stillImageOutput] connections]) {
        for (AVCaptureInputPort *port in [connection inputPorts]) {
            if ([[port mediaType] isEqual:AVMediaTypeVideo]) {
                videoConnection = connection;
                break;
            }
        }
        if (videoConnection) { 
      break; 
    }
    }if ([videoConnection isVideoOrientationSupported])
        [videoConnection setVideoOrientation:self.orientation];

    NSLog(@"about to request a capture from: %@", [self stillImageOutput]);
    [[self stillImageOutput] captureStillImageAsynchronouslyFromConnection:videoConnection
                                                         completionHandler:^(CMSampleBufferRef imageDataSampleBuffer, NSError *error)
                                                           {
                                                               ALAssetsLibraryWriteImageCompletionBlock completionBlock = ^(NSURL *assetURL, NSError *error) {
                                                                   if (error) {
                                                                       NSLog(@"ERROR!!!");
                                                                   }
                                                               };

                                                               if (imageDataSampleBuffer != NULL)
                                                               {                                                                   

                                                                   NSData *imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer];
                                                                   ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];

                                                                   UIImage *image = [[UIImage alloc] initWithData:imageData];
                                                                   [library writeImageToSavedPhotosAlbum:[image CGImage]
                                                                                             orientation:(ALAssetOrientation)[image imageOrientation]
                                                                                         completionBlock:completionBlock];
[[NSNotificationCenter defaultCenter] postNotificationName:kImageCapturedSuccessfully object:nil];

                                                               }

                                                           }];
}

Отправляю уведомление методу saveImageToPhotoAlbum:

- (void)saveImageToPhotoAlbum
{   
    ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
    // Enumerate just the photos and videos group by using ALAssetsGroupSavedPhotos.
    [library enumerateGroupsWithTypes:ALAssetsGroupSavedPhotos usingBlock:^(ALAssetsGroup *group, BOOL *stop) {

        // Within the group enumeration block, filter to enumerate just photos.
        [group setAssetsFilter:[ALAssetsFilter allPhotos]];
        // Chooses the photo at the last index
        [group enumerateAssetsAtIndexes:[NSIndexSet indexSetWithIndex:[group numberOfAssets] - 1] options:0 usingBlock:^(ALAsset *alAsset, NSUInteger index, BOOL *innerStop) {

            // The end of the enumeration is signaled by asset == nil.
            if (alAsset) {
                ALAssetRepresentation *representation = [alAsset defaultRepresentation];
                UIImage *latestPhoto = [UIImage imageWithCGImage:[representation fullScreenImage]];

                self.imageView.image = latestPhoto;
            }
        }];
    } failureBlock: ^(NSError *error) {
        NSLog(@"No groups");
    }];
  }

Там я использовал код для получения последней фотографии и отображения ее на imageView, но она отображает не последнюю, а предыдущую. Поэтому, если я сделаю 3 фотографии, будет отображаться 2, а не 3.

Есть идеи???

Спасибо за помощь!


person user2545330    schedule 22.08.2013    source источник
comment
Я думаю, что индексы начинаются с 0. Так что попробуйте проверить другие вещи, такие как 4,5..... Тогда вы получите идею   -  person SRI    schedule 22.08.2013


Ответы (1)


Ваш код делает то, для чего предназначен. У вас проблема с логикой кода. Вы публикуете уведомление до того, как оно будет завершено с сохранением изображения. Вы должны опубликовать уведомление внутри кода блока завершения записи изображения в библиотеку. И почему бы просто не показать захваченное изображение в imageView вместо того, чтобы читать его из библиотеки??

person Fahri Azimov    schedule 22.08.2013
comment
Рад помочь :) Лучший и простой способ изменить ориентацию изображения: newImage = [[UIImage alloc] initWithCGImage:image.CGImage scale:1. orientation:(UIImageOrientationRight)];. Просто измените параметр ориентации, и все готово;) - person Fahri Azimov; 22.08.2013