DEV Community

ShoheOhtani
ShoheOhtani

Posted on

[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

Top comments (0)