Asynchronously share video instead of fetching it on the main thread

This commit is contained in:
Shadowfacts 2024-03-20 12:23:18 -04:00
parent 1cf3ce48ce
commit f9aee46bbe
1 changed files with 14 additions and 25 deletions

View File

@ -10,46 +10,35 @@ import UIKit
import UniformTypeIdentifiers
import AVFoundation
class VideoActivityItemSource: NSObject, UIActivityItemSource {
let asset: AVAsset
let url: URL
class VideoActivityItemSource: UIActivityItemProvider {
private let asset: AVAsset
private let url: URL
private var tempURL: URL?
init(asset: AVAsset, url: URL) {
self.asset = asset
self.url = url
super.init(placeholderItem: url)
}
func activityViewControllerPlaceholderItem(_ activityViewController: UIActivityViewController) -> Any {
return url
}
func activityViewController(_ activityViewController: UIActivityViewController, thumbnailImageForActivityType activityType: UIActivity.ActivityType?, suggestedSize size: CGSize) -> UIImage? {
#if os(visionOS)
#warning("Use async AVAssetImageGenerator.image(at:)")
return nil
#else
let generator = AVAssetImageGenerator(asset: self.asset)
generator.appliesPreferredTrackTransform = true
if let image = try? generator.copyCGImage(at: .zero, actualTime: nil) {
return UIImage(cgImage: image)
} else {
return nil
override var item: Any {
if let tempURL {
return tempURL
}
#endif
}
func activityViewController(_ activityViewController: UIActivityViewController, itemForActivityType activityType: UIActivity.ActivityType?) -> Any? {
do {
let data = try Data(contentsOf: url)
let tempURL = FileManager.default.temporaryDirectory.appendingPathComponent(url.lastPathComponent)
try data.write(to: tempURL)
self.tempURL = tempURL
return tempURL
} catch {
return nil
return url
}
}
func activityViewController(_ activityViewController: UIActivityViewController, dataTypeIdentifierForActivityType activityType: UIActivity.ActivityType?) -> String {
override func activityViewController(_ activityViewController: UIActivityViewController, dataTypeIdentifierForActivityType activityType: UIActivity.ActivityType?) -> String {
return (UTType(filenameExtension: url.pathExtension) ?? .video).identifier
}
}