私はOperation
とOperationQueue
を使用して、一連のビデオをダウンロードしています。ここに私のダウンロードOperation
があります。操作内からキューにアクセス
import UIKit
import AVFoundation
class VideoDownloader: Operation {
let videoRecord: VideoRecord
init(videoRecord: VideoRecord) {
self.videoRecord = videoRecord
}
override func main() {
if isCancelled {
return
}
let asset = AVURLAsset(url: videoRecord.url)
asset.resourceLoader.setDelegate(self, queue: DispatchQueue.main)
let exporter = AVAssetExportSession(asset: asset, presetName: AVAssetExportPresetHighestQuality)
let filename = "\(videoRecord.id).mp4"
let documentsDirectory = FileManager.default.urls(for: FileManager.SearchPathDirectory.documentDirectory, in: FileManager.SearchPathDomainMask.userDomainMask).last!
let outputURL = documentsDirectory.appendingPathComponent(filename)
exporter?.outputURL = outputURL
exporter?.outputFileType = .mp4
exporter?.exportAsynchronously {
if let error = exporter?.error {
print(error)
} else {
print(outputURL)
}
}
}
}
extension VideoDownloader: AVAssetResourceLoaderDelegate {
}
これは問題なく動作します。しかし、私は下の行について心配しています。
asset.resourceLoader.setDelegate(self, queue: DispatchQueue.main)
現在、私はメインスレッドでデリゲートを設定しています。これはバックグラウンドスレッドで実行されるため、私は正しいとは思わない。私はここで間違っている場合、私を修正してください私は確信していません。
私はそれがキューが現在動作しているキューにキューを設定できると思った。しかし、どのように私は操作クラスからキューにアクセスできますか?
リモートURLからビデオファイルをダウンロードするのにこれを使用していますか? – SeanLintern88
@ SeanLintern88はい、そうです。 – Isuru
TBH、私はこのようなアプローチを見たことがない、通常あなたはUrlSessionDataTaskを使用してビデオをダウンロードするだろう、私はAVAssetExportSessionがバックグラウンドで動作しないことを知っているので誰かがアプリをバックグラウンドすると失敗するだろう – SeanLintern88