Get last image from Photos.app?

后端 未结 13 2111
萌比男神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条回答
  •  猫巷女王i
    2020-11-27 10:06

    Well, here is a solution of how to load last image from gallery with Swift 3 guys:

    func loadLastImageThumb(completion: @escaping (UIImage) -> ()) {
        let imgManager = PHImageManager.default()
        let fetchOptions = PHFetchOptions()
        fetchOptions.fetchLimit = 1
        fetchOptions.sortDescriptors = [NSSortDescriptor(key:"creationDate", ascending: true)]
    
        let fetchResult = PHAsset.fetchAssets(with: PHAssetMediaType.image, options: fetchOptions)
    
        if let last = fetchResult.lastObject {
            let scale = UIScreen.main.scale
            let size = CGSize(width: 100 * scale, height: 100 * scale)
            let options = PHImageRequestOptions()
    
    
            imgManager.requestImage(for: last, targetSize: size, contentMode: PHImageContentMode.aspectFill, options: options, resultHandler: { (image, _) in
                if let image = image {
                    completion(image)
                }
            })
        }
    
    }
    

    If you need more speed, you can also use PHImageRequestOptions and set those:

    options.deliveryMode = .fastFormat
    options.resizeMode = .fast
    

    And this is the way you get it in your viewController (you should replace GalleryManager.manager with your class):

    GalleryManager.manager.loadLastImageThumb { [weak self] (image) in
          DispatchQueue.main.async {
               self?.galleryButton.setImage(image, for: .normal)
          }
    }
    

提交回复
热议问题