430 lines
19 KiB
Swift
430 lines
19 KiB
Swift
import AVFoundation
|
|
import AVKit
|
|
import SnapKit
|
|
import UIKit
|
|
|
|
/// 订单素材的本地只读预览页;分页与缩放不会改变素材选择、下载或拍摄任务。
|
|
@MainActor
|
|
final class DroneMaterialPreviewViewController: UIViewController {
|
|
/// 本地预览列表只有一个媒体分区。
|
|
private enum Section {
|
|
case materials
|
|
}
|
|
|
|
private let items: [DroneMaterial]
|
|
private var currentIndex: Int
|
|
private var lastCollectionSize = CGSize.zero
|
|
private var dataSource: UICollectionViewDiffableDataSource<Section, String>!
|
|
private lazy var collectionView = UICollectionView(frame: .zero, collectionViewLayout: makeCollectionLayout())
|
|
private let closeButton = UIButton(type: .system)
|
|
private let counterLabel = UILabel()
|
|
private let emptyLabel = UILabel()
|
|
private let instructionLabel = UILabel()
|
|
private weak var videoController: AVPlayerViewController?
|
|
private var playbackTask: Task<Void, Never>?
|
|
|
|
/// 以当前素材为起点预览已就绪素材;未就绪项不会被带入预览列表。
|
|
init(items: [DroneMaterial], initialMaterialID: String) {
|
|
var identifiers = Set<String>()
|
|
self.items = items.filter { $0.canPreview && identifiers.insert($0.id).inserted }
|
|
currentIndex = self.items.firstIndex { $0.id == initialMaterialID } ?? 0
|
|
super.init(nibName: nil, bundle: nil)
|
|
modalPresentationStyle = .fullScreen
|
|
modalTransitionStyle = .crossDissolve
|
|
}
|
|
|
|
@available(*, unavailable)
|
|
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
|
|
|
|
override var preferredStatusBarStyle: UIStatusBarStyle { .lightContent }
|
|
|
|
override func viewDidLoad() {
|
|
super.viewDidLoad()
|
|
setupUI()
|
|
setupConstraints()
|
|
setupDataSource()
|
|
applySnapshot()
|
|
}
|
|
|
|
override func viewDidLayoutSubviews() {
|
|
super.viewDidLayoutSubviews()
|
|
guard collectionView.bounds.width > 0, collectionView.bounds.size != lastCollectionSize else { return }
|
|
lastCollectionSize = collectionView.bounds.size
|
|
collectionView.collectionViewLayout.invalidateLayout()
|
|
collectionView.setContentOffset(CGPoint(x: CGFloat(currentIndex) * collectionView.bounds.width, y: 0), animated: false)
|
|
}
|
|
|
|
override func viewWillDisappear(_ animated: Bool) {
|
|
super.viewWillDisappear(animated)
|
|
if isBeingDismissed || navigationController?.isBeingDismissed == true {
|
|
playbackTask?.cancel()
|
|
videoController?.player?.pause()
|
|
}
|
|
}
|
|
|
|
private func setupUI() {
|
|
view.backgroundColor = UIColor(hex: 0x141820)
|
|
view.accessibilityIdentifier = "drone.material.preview"
|
|
collectionView.backgroundColor = .clear
|
|
collectionView.isPagingEnabled = true
|
|
collectionView.showsHorizontalScrollIndicator = false
|
|
collectionView.alwaysBounceHorizontal = items.count > 1
|
|
collectionView.contentInsetAdjustmentBehavior = .never
|
|
collectionView.accessibilityIdentifier = "drone.material.preview.pages"
|
|
collectionView.delegate = self
|
|
collectionView.register(DroneMaterialPreviewCell.self, forCellWithReuseIdentifier: DroneMaterialPreviewCell.reuseIdentifier)
|
|
|
|
closeButton.setImage(UIImage(systemName: "xmark", withConfiguration: UIImage.SymbolConfiguration(pointSize: 18, weight: .regular)), for: .normal)
|
|
closeButton.tintColor = .white
|
|
closeButton.accessibilityLabel = "关闭素材预览"
|
|
closeButton.accessibilityIdentifier = "drone.material.preview.close"
|
|
closeButton.addTarget(self, action: #selector(closeTapped), for: .touchUpInside)
|
|
|
|
counterLabel.textColor = UIColor.white.withAlphaComponent(0.75)
|
|
counterLabel.font = .monospacedDigitSystemFont(ofSize: 13, weight: .medium)
|
|
counterLabel.textAlignment = .center
|
|
counterLabel.accessibilityIdentifier = "drone.material.preview.counter"
|
|
updateCounter()
|
|
|
|
emptyLabel.text = "暂无可预览的就绪素材"
|
|
emptyLabel.textColor = UIColor.white.withAlphaComponent(0.7)
|
|
emptyLabel.font = .systemFont(ofSize: 15)
|
|
emptyLabel.textAlignment = .center
|
|
emptyLabel.numberOfLines = 0
|
|
emptyLabel.isHidden = !items.isEmpty
|
|
|
|
instructionLabel.text = items.count > 1 ? "双指或双击缩放 · 左右滑动切换" : "双指或双击缩放"
|
|
instructionLabel.textColor = UIColor.white.withAlphaComponent(0.4)
|
|
instructionLabel.font = .systemFont(ofSize: 11)
|
|
instructionLabel.textAlignment = .center
|
|
instructionLabel.isHidden = items.isEmpty
|
|
|
|
view.addSubview(collectionView)
|
|
view.addSubview(emptyLabel)
|
|
view.addSubview(closeButton)
|
|
view.addSubview(counterLabel)
|
|
view.addSubview(instructionLabel)
|
|
}
|
|
|
|
private func setupConstraints() {
|
|
collectionView.snp.makeConstraints { make in
|
|
make.edges.equalToSuperview()
|
|
}
|
|
closeButton.snp.makeConstraints { make in
|
|
make.top.equalTo(view.safeAreaLayoutGuide).offset(4)
|
|
make.trailing.equalToSuperview().inset(10)
|
|
make.size.equalTo(44)
|
|
}
|
|
counterLabel.snp.makeConstraints { make in
|
|
make.centerY.equalTo(closeButton)
|
|
make.centerX.equalToSuperview()
|
|
make.leading.greaterThanOrEqualToSuperview().offset(64)
|
|
make.trailing.lessThanOrEqualTo(closeButton.snp.leading).offset(-8)
|
|
}
|
|
emptyLabel.snp.makeConstraints { make in
|
|
make.center.equalToSuperview()
|
|
make.leading.trailing.equalToSuperview().inset(32)
|
|
}
|
|
instructionLabel.snp.makeConstraints { make in
|
|
make.leading.trailing.equalToSuperview().inset(24)
|
|
make.bottom.equalTo(view.safeAreaLayoutGuide).inset(16)
|
|
}
|
|
}
|
|
|
|
private func setupDataSource() {
|
|
dataSource = UICollectionViewDiffableDataSource<Section, String>(collectionView: collectionView) { [weak self] collectionView, indexPath, identifier in
|
|
guard let self, let material = self.items.first(where: { $0.id == identifier }),
|
|
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: DroneMaterialPreviewCell.reuseIdentifier, for: indexPath) as? DroneMaterialPreviewCell else {
|
|
return UICollectionViewCell()
|
|
}
|
|
cell.configure(material: material)
|
|
cell.onPlayLocalVideo = { [weak self, weak cell] in
|
|
self?.playLocalVideo(material, sourceCell: cell)
|
|
}
|
|
return cell
|
|
}
|
|
}
|
|
|
|
private func applySnapshot() {
|
|
var snapshot = NSDiffableDataSourceSnapshot<Section, String>()
|
|
snapshot.appendSections([.materials])
|
|
snapshot.appendItems(items.map(\.id))
|
|
dataSource.apply(snapshot, animatingDifferences: false) { [weak self] in
|
|
guard let self, self.collectionView.bounds.width > 0 else { return }
|
|
self.collectionView.layoutIfNeeded()
|
|
self.collectionView.setContentOffset(CGPoint(x: CGFloat(self.currentIndex) * self.collectionView.bounds.width, y: 0), animated: false)
|
|
}
|
|
}
|
|
|
|
private func makeCollectionLayout() -> UICollectionViewLayout {
|
|
let layout = UICollectionViewFlowLayout()
|
|
layout.scrollDirection = .horizontal
|
|
layout.minimumLineSpacing = 0
|
|
layout.minimumInteritemSpacing = 0
|
|
return layout
|
|
}
|
|
|
|
private func updateCounter() {
|
|
counterLabel.text = items.isEmpty ? "0 / 0" : "\(currentIndex + 1) / \(items.count)"
|
|
counterLabel.accessibilityLabel = items.isEmpty ? "没有可预览素材" : "第 \(currentIndex + 1) 项,共 \(items.count) 项"
|
|
}
|
|
|
|
private func updateCurrentIndex() {
|
|
guard collectionView.bounds.width > 0, !items.isEmpty else { return }
|
|
currentIndex = min(max(Int(round(collectionView.contentOffset.x / collectionView.bounds.width)), 0), items.count - 1)
|
|
updateCounter()
|
|
}
|
|
|
|
private func playLocalVideo(_ material: DroneMaterial, sourceCell: DroneMaterialPreviewCell?) {
|
|
guard playbackTask == nil, let url = DroneMaterialPreviewCell.localVideoURL(for: material) else { return }
|
|
sourceCell?.setVideoValidationInProgress(true)
|
|
playbackTask = Task { @MainActor [weak self, weak sourceCell] in
|
|
let playable = (try? await AVURLAsset(url: url).load(.isPlayable)) == true
|
|
guard let self else { return }
|
|
self.playbackTask = nil
|
|
sourceCell?.setVideoValidationInProgress(false)
|
|
guard !Task.isCancelled, self.view.window != nil, self.presentedViewController == nil,
|
|
self.items.indices.contains(self.currentIndex), self.items[self.currentIndex].id == material.id else { return }
|
|
guard playable else {
|
|
sourceCell?.showUnavailableVideo()
|
|
return
|
|
}
|
|
let controller = AVPlayerViewController()
|
|
let player = AVPlayer(url: url)
|
|
controller.player = player
|
|
self.videoController = controller
|
|
self.present(controller, animated: true) { player.play() }
|
|
}
|
|
}
|
|
|
|
@objc private func closeTapped() {
|
|
playbackTask?.cancel()
|
|
playbackTask = nil
|
|
videoController?.player?.pause()
|
|
dismiss(animated: true)
|
|
}
|
|
}
|
|
|
|
extension DroneMaterialPreviewViewController: UICollectionViewDelegateFlowLayout {
|
|
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
|
|
collectionView.bounds.size
|
|
}
|
|
|
|
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { updateCurrentIndex() }
|
|
|
|
func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) { updateCurrentIndex() }
|
|
}
|
|
|
|
/// 单项本地素材预览,完整呈现图片并提供独立缩放,不触发远程请求。
|
|
@MainActor
|
|
private final class DroneMaterialPreviewCell: UICollectionViewCell, UIScrollViewDelegate {
|
|
static let reuseIdentifier = "DroneMaterialPreviewCell"
|
|
|
|
/// 用户明确点击本地可播放视频后通知预览页。
|
|
var onPlayLocalVideo: (() -> Void)?
|
|
|
|
private let scrollView = DroneMaterialPreviewZoomView()
|
|
private var imageView: UIImageView { scrollView.imageView }
|
|
private let titleLabel = UILabel()
|
|
private let typeLabel = UILabel()
|
|
private let zoomLabel = UILabel()
|
|
private let unavailableImageLabel = UILabel()
|
|
private let playButton = UIButton(type: .system)
|
|
private var imageAspectRatio: CGFloat = 9 / 16
|
|
|
|
override init(frame: CGRect) {
|
|
super.init(frame: frame)
|
|
setupUI()
|
|
setupConstraints()
|
|
}
|
|
|
|
@available(*, unavailable)
|
|
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
|
|
|
|
override func prepareForReuse() {
|
|
super.prepareForReuse()
|
|
onPlayLocalVideo = nil
|
|
scrollView.setZoomScale(1, animated: false)
|
|
imageView.image = nil
|
|
playButton.isEnabled = true
|
|
}
|
|
|
|
/// 只读取本地图片资源;视频无本地片源时明确显示静帧说明。
|
|
func configure(material: DroneMaterial) {
|
|
scrollView.setZoomScale(1, animated: false)
|
|
scrollView.setContentOffset(.zero, animated: false)
|
|
let image: UIImage?
|
|
if material.kind == .photo, let url = material.previewURL, url.isFileURL {
|
|
image = UIImage(contentsOfFile: url.path) ?? UIImage(named: material.previewAssetName)
|
|
} else {
|
|
image = UIImage(named: material.previewAssetName)
|
|
}
|
|
imageView.image = image
|
|
imageView.accessibilityLabel = material.title
|
|
titleLabel.text = "\(material.title) · 演示素材"
|
|
imageAspectRatio = image.map { $0.size.height / max($0.size.width, 1) } ?? 9 / 16
|
|
unavailableImageLabel.isHidden = image != nil
|
|
playButton.isHidden = Self.localVideoURL(for: material) == nil
|
|
switch material.kind {
|
|
case .photo:
|
|
typeLabel.text = "照片 · 本地演示图片"
|
|
case .video:
|
|
typeLabel.text = playButton.isHidden ? "视频 · 本地演示静帧 · 暂无演示视频" : "视频 · 本地演示视频"
|
|
}
|
|
zoomLabel.text = "100%"
|
|
updateMediaConstraints()
|
|
setNeedsLayout()
|
|
}
|
|
|
|
/// 只接受实际存在的本地文件,远程地址不会被交给播放器。
|
|
static func localVideoURL(for material: DroneMaterial) -> URL? {
|
|
guard material.kind == .video, let url = material.previewURL, url.isFileURL,
|
|
FileManager.default.fileExists(atPath: url.path),
|
|
["mp4", "mov", "m4v"].contains(url.pathExtension.lowercased()) else { return nil }
|
|
return url
|
|
}
|
|
|
|
/// 校验本地视频期间锁定播放按钮,避免重复创建播放器。
|
|
func setVideoValidationInProgress(_ inProgress: Bool) {
|
|
playButton.isEnabled = !inProgress
|
|
playButton.accessibilityLabel = inProgress ? "正在检查本地视频" : "播放本地演示视频"
|
|
}
|
|
|
|
/// 本地文件无法播放时保留真实静帧,不展示虚假的进度。
|
|
func showUnavailableVideo() {
|
|
playButton.isHidden = true
|
|
typeLabel.text = "视频 · 本地演示静帧 · 暂无可播放演示视频"
|
|
}
|
|
|
|
func viewForZooming(in scrollView: UIScrollView) -> UIView? { imageView }
|
|
|
|
func scrollViewDidZoom(_ scrollView: UIScrollView) {
|
|
zoomLabel.text = "\(Int((scrollView.zoomScale * 100).rounded()))%"
|
|
}
|
|
|
|
private func setupUI() {
|
|
scrollView.minimumZoomScale = 1
|
|
scrollView.maximumZoomScale = 3
|
|
scrollView.delegate = self
|
|
scrollView.showsHorizontalScrollIndicator = false
|
|
scrollView.showsVerticalScrollIndicator = false
|
|
scrollView.contentInsetAdjustmentBehavior = .never
|
|
scrollView.bouncesZoom = true
|
|
scrollView.accessibilityIdentifier = "drone.material.preview.zoomSurface"
|
|
imageView.contentMode = .scaleAspectFit
|
|
imageView.isAccessibilityElement = true
|
|
imageView.accessibilityIdentifier = "drone.material.preview.image"
|
|
|
|
titleLabel.font = .systemFont(ofSize: 13, weight: .medium)
|
|
titleLabel.textColor = UIColor.white.withAlphaComponent(0.75)
|
|
titleLabel.textAlignment = .center
|
|
titleLabel.numberOfLines = 2
|
|
titleLabel.accessibilityIdentifier = "drone.material.preview.title"
|
|
typeLabel.font = .systemFont(ofSize: 11)
|
|
typeLabel.textColor = UIColor.white.withAlphaComponent(0.5)
|
|
typeLabel.textAlignment = .center
|
|
typeLabel.numberOfLines = 2
|
|
typeLabel.accessibilityIdentifier = "drone.material.preview.type"
|
|
zoomLabel.font = .monospacedDigitSystemFont(ofSize: 11, weight: .regular)
|
|
zoomLabel.textColor = UIColor.white.withAlphaComponent(0.4)
|
|
zoomLabel.textAlignment = .center
|
|
zoomLabel.accessibilityIdentifier = "drone.material.preview.zoom"
|
|
|
|
unavailableImageLabel.text = "暂无本地演示图片"
|
|
unavailableImageLabel.font = .systemFont(ofSize: 14)
|
|
unavailableImageLabel.textColor = UIColor.white.withAlphaComponent(0.65)
|
|
unavailableImageLabel.textAlignment = .center
|
|
unavailableImageLabel.numberOfLines = 0
|
|
playButton.setImage(UIImage(systemName: "play.circle.fill", withConfiguration: UIImage.SymbolConfiguration(pointSize: 58, weight: .regular)), for: .normal)
|
|
playButton.tintColor = .white
|
|
playButton.accessibilityLabel = "播放本地演示视频"
|
|
playButton.accessibilityIdentifier = "drone.material.preview.play"
|
|
playButton.addTarget(self, action: #selector(playTapped), for: .touchUpInside)
|
|
|
|
contentView.addSubview(scrollView)
|
|
contentView.addSubview(unavailableImageLabel)
|
|
contentView.addSubview(titleLabel)
|
|
contentView.addSubview(typeLabel)
|
|
contentView.addSubview(zoomLabel)
|
|
contentView.addSubview(playButton)
|
|
let doubleTap = UITapGestureRecognizer(target: self, action: #selector(doubleTapped(_:)))
|
|
doubleTap.numberOfTapsRequired = 2
|
|
scrollView.addGestureRecognizer(doubleTap)
|
|
}
|
|
|
|
private func setupConstraints() {
|
|
updateMediaConstraints()
|
|
titleLabel.snp.makeConstraints { make in
|
|
make.top.equalTo(scrollView.snp.bottom).offset(16)
|
|
make.leading.trailing.equalToSuperview().inset(24)
|
|
}
|
|
typeLabel.snp.makeConstraints { make in
|
|
make.top.equalTo(titleLabel.snp.bottom).offset(6)
|
|
make.leading.trailing.equalTo(titleLabel)
|
|
}
|
|
zoomLabel.snp.makeConstraints { make in
|
|
make.top.equalTo(typeLabel.snp.bottom).offset(6)
|
|
make.leading.trailing.equalTo(titleLabel)
|
|
}
|
|
unavailableImageLabel.snp.makeConstraints { make in
|
|
make.center.equalTo(scrollView)
|
|
make.leading.trailing.equalToSuperview().inset(32)
|
|
}
|
|
playButton.snp.makeConstraints { make in
|
|
make.center.equalTo(scrollView)
|
|
make.size.equalTo(72)
|
|
}
|
|
}
|
|
|
|
private func updateMediaConstraints() {
|
|
scrollView.snp.remakeConstraints { make in
|
|
make.leading.trailing.equalToSuperview()
|
|
make.centerY.equalToSuperview().offset(-28)
|
|
make.height.equalTo(scrollView.snp.width).multipliedBy(imageAspectRatio).priority(999)
|
|
make.height.lessThanOrEqualToSuperview().multipliedBy(0.6)
|
|
}
|
|
}
|
|
|
|
@objc private func playTapped() { onPlayLocalVideo?() }
|
|
|
|
@objc private func doubleTapped(_ gesture: UITapGestureRecognizer) {
|
|
guard imageView.image != nil else { return }
|
|
if scrollView.zoomScale > 1 {
|
|
scrollView.setZoomScale(1, animated: true)
|
|
return
|
|
}
|
|
let point = gesture.location(in: imageView)
|
|
let targetScale: CGFloat = 3
|
|
let size = CGSize(width: scrollView.bounds.width / targetScale, height: scrollView.bounds.height / targetScale)
|
|
scrollView.zoom(to: CGRect(x: point.x - size.width / 2, y: point.y - size.height / 2, width: size.width, height: size.height), animated: true)
|
|
}
|
|
}
|
|
|
|
/// 在自身视口完成布局后设置图片尺寸,避免依赖集合单元与约束子树的布局先后顺序。
|
|
@MainActor
|
|
private final class DroneMaterialPreviewZoomView: UIScrollView {
|
|
/// 由素材单元配置的图片,也是 UIScrollView 的缩放目标。
|
|
let imageView = UIImageView()
|
|
private var lastViewportSize = CGSize.zero
|
|
|
|
override init(frame: CGRect) {
|
|
super.init(frame: frame)
|
|
imageView.isUserInteractionEnabled = true
|
|
addSubview(imageView)
|
|
}
|
|
|
|
@available(*, unavailable)
|
|
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
|
|
|
|
override func layoutSubviews() {
|
|
super.layoutSubviews()
|
|
let viewportSize = bounds.size
|
|
guard viewportSize.width > 0, viewportSize.height > 0, viewportSize != lastViewportSize else { return }
|
|
lastViewportSize = viewportSize
|
|
setZoomScale(1, animated: false)
|
|
imageView.frame = CGRect(origin: .zero, size: viewportSize)
|
|
contentSize = viewportSize
|
|
setContentOffset(.zero, animated: false)
|
|
}
|
|
}
|