2

I want the last image saved in camera roll. I have searched for it but m getting result for ALAssetsLibrary which is deprecated in iOS 9 so please provide me solution for this because m not getting proper solution for that.

I want solution in objective C.

Bhagyashree mahajan
  • 511
  • 1
  • 6
  • 12

2 Answers2

2

Please check this code... it may help you.

PHFetchOptions *fetchOptions = [[PHFetchOptions alloc] init];
fetchOptions.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:YES]];
PHFetchResult *fetchResult = [PHAsset fetchAssetsWithMediaType:PHAssetMediaTypeImage options:fetchOptions];
PHAsset *lastAsset = [fetchResult lastObject];
[[PHImageManager defaultManager] requestImageForAsset:lastAsset
                                          targetSize:self.photoLibraryButton.bounds.size
                                         contentMode:PHImageContentModeAspectFill
                                             options:PHImageRequestOptionsVersionCurrent
                                       resultHandler:^(UIImage *result, NSDictionary *info) {

                                           dispatch_async(dispatch_get_main_queue(), ^{

                                               [[self photoLibraryButton] setImage:result forState:UIControlStateNormal];

                                           });
                                       }];
yankit Patel
  • 308
  • 1
  • 11
2

In iOS 8, Apple added the Photos library which makes for easier querying.

import UIKit
import Photos

struct LastPhotoRetriever {
    func queryLastPhoto(resizeTo size: CGSize?, queryCallback: (UIImage? -> Void)) {
        let fetchOptions = PHFetchOptions()
        fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]

//        fetchOptions.fetchLimit = 1 // This is available in iOS 9.

        if let fetchResult = PHAsset.fetchAssetsWithMediaType(PHAssetMediaType.Image, options: fetchOptions) {
            if let asset = fetchResult.firstObject as? PHAsset {
                let manager = PHImageManager.defaultManager()

                // If you already know how you want to resize, 
                // great, otherwise, use full-size.
                let targetSize = size == nil ? CGSize(width: asset.pixelWidth, height: asset.pixelHeight) : size!

                // I arbitrarily chose AspectFit here. AspectFill is 
                // also available.
                manager.requestImageForAsset(asset,
                    targetSize: targetSize,
                    contentMode: .AspectFit,
                    options: nil,
                    resultHandler: { image, info in

                    queryCallback(image)
                })
            }
        }
    }
}
ashmi123
  • 690
  • 1
  • 6
  • 21