如何从iOS上的Camera Roll中检索最近的照片?

use*_*127 28 objective-c ios

我正在努力弄清楚如何在没有用户干预的情况下以编程方式检索相机胶卷中的最新照片.要清楚,我不想使用图像选择器,我希望应用程序在应用程序打开时自动抓取最新的照片.

我知道这是可能的,因为我看过类似的应用程序这样做,但我似乎无法找到任何信息.

Art*_*pie 46

一种方法是使用AssetsLibrary并使用n - 1作为枚举的索引.

ALAssetsLibrary *assetsLibrary = [[ALAssetsLibrary alloc] init];
[assetsLibrary enumerateGroupsWithTypes:ALAssetsGroupSavedPhotos
                             usingBlock:^(ALAssetsGroup *group, BOOL *stop) {
                                 if (nil != group) {
                                     // be sure to filter the group so you only get photos
                                     [group setAssetsFilter:[ALAssetsFilter allPhotos]];

                                     if (group.numberOfAssets > 0) {
                                         [group enumerateAssetsAtIndexes:[NSIndexSet indexSetWithIndex:group.numberOfAssets - 1]
                                                                 options:0
                                                              usingBlock:^(ALAsset *result, NSUInteger index, BOOL *stop) {
                                                                  if (nil != result) {
                                                                      ALAssetRepresentation *repr = [result defaultRepresentation];
                                                                      // this is the most recent saved photo
                                                                      UIImage *img = [UIImage imageWithCGImage:[repr fullResolutionImage]];
                                                                      // we only need the first (most recent) photo -- stop the enumeration
                                                                      *stop = YES;
                                                                  }
                                                              }];
                                     }
                                 }

                                 *stop = NO;
                             } failureBlock:^(NSError *error) {
                                 NSLog(@"error: %@", error);
                             }];
Run Code Online (Sandbox Code Playgroud)

  • 好的解决方案,谢谢!注意:还应该确保group.numberOfAssets> 0以避免[group enumerateAssetsAtIndexes:-1]的越界崩溃 (6认同)

Her*_*III 24

您可以反过来列出列表,而不是弄乱索引.如果您想要最新的图像,或者您希望首先使用最新图像在UICollectionView中列出图像,则此模式很有效.

返回最新图像的示例:

[group enumerateAssetsWithOptions:NSEnumerationReverse usingBlock:^(ALAsset *asset, NSUInteger index, BOOL *stop) {
    if (asset) {
        ALAssetRepresentation *repr = [asset defaultRepresentation];
        UIImage *img = [UIImage imageWithCGImage:[repr fullResolutionImage]];
        *stop = YES;
    }
}];
Run Code Online (Sandbox Code Playgroud)


swi*_*ams 11

在iOS 8中,Apple添加了Photos库,以便于查询.在iOS 9中,ALAssetLibrary弃用.

这是一些Swift代码,用于获取使用该框架拍摄的最新照片.

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)
                })
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


Jos*_*nor 7

Swift 3.0:

1)在您的类声明之前在标题中导入Photos框架.

import Photos
Run Code Online (Sandbox Code Playgroud)


2)添加以下方法,返回最后一个图像.

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

    let requestOptions = PHImageRequestOptions()
    requestOptions.isSynchronous = true

    let fetchResult = PHAsset.fetchAssets(with: PHAssetMediaType.image, options: fetchOptions)
    if let asset = fetchResult.firstObject {
        let manager = PHImageManager.default()

        let targetSize = size == nil ? CGSize(width: asset.pixelWidth, height: asset.pixelHeight) : size!

        manager.requestImage(for: asset,
                             targetSize: targetSize,
                             contentMode: .aspectFit,
                             options: requestOptions,
                             resultHandler: { image, info in
                                queryCallback(image)
        })
    }

}
Run Code Online (Sandbox Code Playgroud)


3)然后在你的应用程序中的某个地方调用此方法(可能是按钮操作):

@IBAction func pressedLastPictureAttachmentButton(_ sender: Any) {
    queryLastPhoto(resizeTo: nil){
        image in
        print(image)
    }
}
Run Code Online (Sandbox Code Playgroud)


Lia*_*iam 6

要添加到Art Gillespie的答案,使用fullResolutionImage原始图像 - 根据设备在拍照时的方向 - 可能会让您倒置或-90°图像.

要获得经过修改但优化的图像,请使用fullScreenImage....

 UIImage *img = [UIImage imageWithCGImage:[repr fullScreenImage]];
Run Code Online (Sandbox Code Playgroud)