Get last image from Photos.app?

后端 未结 13 2041
萌比男神i
萌比男神i 2020-11-27 09:50

I have seen other apps do it where you can import the last photo from the Photos app for quick use but as far as I know, I only know how to get A image and not the last (mos

13条回答
  •  [愿得一人]
    2020-11-27 10:22

    iBrad's example includes an iOS8 snippet that apparently works, but I found myself confused by the return type he described. Here is a snippet that grabs the last image, including options for version and size requirements.

    Of note are the ability to request a specific version (original, current) and size. In my case, as I wish to apply the returned image to a button, I request it sized and scaled to fit the button I'm applying it to:

    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];
    
                                               });
                                           }];
    

提交回复
热议问题