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 UniformTypeIdentifiers
import AVFoundation import AVFoundation
class VideoActivityItemSource: NSObject, UIActivityItemSource { class VideoActivityItemSource: UIActivityItemProvider {
let asset: AVAsset private let asset: AVAsset
let url: URL private let url: URL
private var tempURL: URL?
init(asset: AVAsset, url: URL) { init(asset: AVAsset, url: URL) {
self.asset = asset self.asset = asset
self.url = url self.url = url
super.init(placeholderItem: url)
} }
func activityViewControllerPlaceholderItem(_ activityViewController: UIActivityViewController) -> Any { override var item: Any {
return url if let tempURL {
} return tempURL
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
} }
#endif
}
func activityViewController(_ activityViewController: UIActivityViewController, itemForActivityType activityType: UIActivity.ActivityType?) -> Any? {
do { do {
let data = try Data(contentsOf: url) let data = try Data(contentsOf: url)
let tempURL = FileManager.default.temporaryDirectory.appendingPathComponent(url.lastPathComponent) let tempURL = FileManager.default.temporaryDirectory.appendingPathComponent(url.lastPathComponent)
try data.write(to: tempURL) try data.write(to: tempURL)
self.tempURL = tempURL
return tempURL return tempURL
} catch { } 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 return (UTType(filenameExtension: url.pathExtension) ?? .video).identifier
} }
} }