DEV Community

ShoheOhtani
ShoheOhtani

Posted on

3 2

[Swift] How to fetch only screenShot & screenRecording from photo library

Apple doesn't prepare enum for screenRecording like .photoScreenshot in PHAssetMediaSubtype. However screenRecording asset has mediaSubtype which is 524288.

import SwiftUI
import Photos

...
var photos: [Asset] = []

func fetchPhotos() {
    let options = PHFetchOptions()
    options.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]
    options.predicate = NSPredicate(format: "((mediaSubtype & %d) != 0 || (mediaSubtype & %d) != 0)", PHAssetMediaSubtype.photoScreenshot.rawValue, 524288)
    options.includeHiddenAssets = false

    let result = PHAsset.fetchAssets(with: options)
    result.enumerateObjects { asset, index, _ in
        Task {
            guard let image: UIImage = await self.getImageFromAsset(asset: asset, size: CGSize(width: self.assetSize, height: self.assetSize)) else { return }
            DispatchQueue.main.async { [weak self] in
                self?.photos.append(Asset(asset: asset, image: image))
            }
        }
    }
}

private func getImageFromAsset(asset: PHAsset, size: CGSize) async -> UIImage? {
    return await withCheckedContinuation { continuation in
        let manager = PHCachingImageManager()
        manager.allowsCachingHighQualityImages = true

        let options = PHImageRequestOptions()
        options.deliveryMode = .highQualityFormat
        options.isSynchronous = false
        manager.requestImage(for: asset, targetSize: size, contentMode: .aspectFill, options: options) { image, _ in
            continuation.resume(returning: image)
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay