feat: 完善机巢模拟调试与素材交付交互

增加禁飞期间的设备指令拦截及本地模拟拍摄流程;适配订单素材库和景区空境库,完善素材筛选、预览与下载;订单交付入口改为方式选择弹窗并复用云端上传。补充单元测试、接口记录和模拟器截图。
This commit is contained in:
2026-10-30 09:59:11 +08:00
parent e827bf8725
commit b95b251de1
100 changed files with 7256 additions and 500 deletions
@@ -1,14 +1,15 @@
import Kingfisher
import SnapKit
import UIKit
/// 景区素材模块的局部样式,可独立于机巢业务使用。
@MainActor
enum ScenicMaterialsStyle {
static let primary = UIColor(hex: 0x3164FF)
static let primary = UIColor(hex: 0x066BFF)
static let background = UIColor.white
static let text = UIColor(hex: 0x20242C)
static let secondary = UIColor(hex: 0x9297A1)
static let border = UIColor(hex: 0xECEEF2)
static let text = UIColor(hex: 0x151515)
static let secondary = UIColor(hex: 0x8490A5)
static let border = UIColor(hex: 0xE7E9EF)
static let success = UIColor(hex: 0x17986A)
static let warning = UIColor(hex: 0xD98926)
@@ -79,8 +80,11 @@ final class ScenicMaterialClipCell: UICollectionViewCell {
/// 显示片段及本机演示传输状态;首段大图额外显示分辨率和体积。
func configure(clip: ScenicMaterialClip, selected: Bool, isSelectionEnabled: Bool,
statusText: String? = nil, progress: Double? = nil, isHero: Bool = false) {
cover.image = UIImage(named: clip.coverAssetName)
ordinalLabel.text = String(format: "片段 %02d", clip.ordinal)
cover.kf.cancelDownloadTask()
if clip.isRemote {
cover.kf.setImage(with: clip.coverURL, placeholder: UIImage(systemName: "photo"))
} else { cover.image = UIImage(named: clip.coverAssetName) }
ordinalLabel.text = clip.fileLabel ?? String(format: "片段 %02d", clip.ordinal)
metadataLabel.text = isHero ? "\(clip.durationText) · \(clip.resolution) · \(clip.sizeText)" : clip.durationText
metadataLabel.font = .monospacedDigitSystemFont(ofSize: isHero ? 11 : 10, weight: .regular)
selectionButton.setImage(UIImage(systemName: selected ? "checkmark.circle.fill" : "circle",
@@ -269,27 +273,46 @@ final class ScenicMaterialExpandCell: UICollectionViewCell {
@objc private func tapped() { onToggleExpanded?() }
}
/// 固定底部的选择/下载摘要,不直接持有 ViewModel 或执行文件操作。
/// 固定底部的选择/下载摘要,由页面显式传入布局和状态,不执行文件操作。
@MainActor
final class ScenicMaterialsFooterView: UIView {
/// 选择态左右排列;传输态显示摘要、进度和通栏按钮;结果态显示摘要和操作行。
enum Layout { case selection, progress, result }
/// 当前阶段的主要操作,例如下载、继续或重试。
var onPrimaryTap: (() -> Void)?
/// 当前阶段的次要操作,例如取消或继续选择。
var onSecondaryTap: (() -> Void)?
private let titleLabel = ScenicMaterialsStyle.label(size: 14, weight: .medium)
private let detailLabel = ScenicMaterialsStyle.label(size: 10, color: ScenicMaterialsStyle.secondary)
private let titleLabel = ScenicMaterialsStyle.label(size: 14)
private let detailLabel = ScenicMaterialsStyle.label(size: 11, color: ScenicMaterialsStyle.secondary)
private let primaryButton = UIButton(type: .custom)
private let secondaryButton = UIButton(type: .custom)
private let progressView = UIProgressView(progressViewStyle: .bar)
private let activity = UIActivityIndicatorView(style: .medium)
private let summaryRow = UIStackView()
private let actionRow = UIStackView()
private let stack = UIStackView()
private var currentLayout: Layout?
private var hasSecondaryAction = false
/// 创建随安全区延伸的白色底栏。
override init(frame: CGRect) {
super.init(frame: frame)
setupUI()
setupConstraints()
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
private func setupUI() {
backgroundColor = .white
titleLabel.numberOfLines = 2
titleLabel.accessibilityIdentifier = "scenic.materials.footer.title"
detailLabel.numberOfLines = 2
primaryButton.titleLabel?.font = .systemFont(ofSize: 14, weight: .semibold)
primaryButton.titleLabel?.numberOfLines = 2
detailLabel.accessibilityIdentifier = "scenic.materials.footer.detail"
primaryButton.titleLabel?.font = .systemFont(ofSize: 15, weight: .semibold)
primaryButton.titleLabel?.numberOfLines = 1
primaryButton.titleLabel?.textAlignment = .center
primaryButton.setTitleColor(.white, for: .normal)
primaryButton.setTitleColor(.white, for: .disabled)
@@ -297,64 +320,137 @@ final class ScenicMaterialsFooterView: UIView {
primaryButton.clipsToBounds = true
primaryButton.accessibilityIdentifier = "scenic.materials.primary"
primaryButton.addTarget(self, action: #selector(primaryTapped), for: .touchUpInside)
secondaryButton.tintColor = ScenicMaterialsStyle.primary
secondaryButton.setTitleColor(ScenicMaterialsStyle.primary, for: .normal)
secondaryButton.titleLabel?.font = .systemFont(ofSize: 13)
secondaryButton.setTitleColor(ScenicMaterialsStyle.secondary, for: .normal)
secondaryButton.titleLabel?.font = .systemFont(ofSize: 15)
secondaryButton.titleLabel?.numberOfLines = 1
secondaryButton.titleLabel?.textAlignment = .center
secondaryButton.layer.cornerRadius = 10
secondaryButton.accessibilityIdentifier = "scenic.materials.secondary"
secondaryButton.addTarget(self, action: #selector(secondaryTapped), for: .touchUpInside)
progressView.progressTintColor = ScenicMaterialsStyle.primary
progressView.trackTintColor = ScenicMaterialsStyle.border
let labels = UIStackView(arrangedSubviews: [titleLabel, detailLabel])
labels.axis = .vertical
labels.spacing = 5
let row = UIStackView(arrangedSubviews: [labels, primaryButton])
row.axis = .horizontal
row.spacing = 12
row.alignment = .center
let stack = UIStackView(arrangedSubviews: [row, progressView, secondaryButton])
progressView.trackTintColor = UIColor(hex: 0xE7EDF7)
progressView.accessibilityIdentifier = "scenic.materials.footer.progress"
activity.color = .white
activity.hidesWhenStopped = true
activity.isUserInteractionEnabled = false
activity.accessibilityIdentifier = "scenic.materials.footer.activity"
primaryButton.addSubview(activity)
summaryRow.axis = .horizontal
summaryRow.alignment = .center
summaryRow.spacing = 8
actionRow.axis = .horizontal
actionRow.alignment = .center
actionRow.spacing = 16
stack.axis = .vertical
stack.spacing = 10
let separator = UIView()
separator.backgroundColor = ScenicMaterialsStyle.border
addSubview(separator)
stack.spacing = 8
addSubview(stack)
separator.snp.makeConstraints { $0.top.leading.trailing.equalToSuperview(); $0.height.equalTo(0.5) }
stack.snp.makeConstraints {
$0.top.equalToSuperview().offset(14)
$0.leading.trailing.equalToSuperview().inset(20)
$0.bottom.equalTo(safeAreaLayoutGuide).inset(12)
}
primaryButton.snp.makeConstraints { $0.width.equalTo(158); $0.height.equalTo(46) }
progressView.snp.makeConstraints { $0.height.equalTo(3).priority(999) }
secondaryButton.snp.makeConstraints { $0.height.equalTo(32).priority(999) }
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
private func setupConstraints() {
stack.snp.makeConstraints {
$0.top.equalToSuperview().offset(14)
$0.leading.trailing.equalToSuperview().inset(18)
$0.bottom.equalTo(safeAreaLayoutGuide).inset(14)
}
primaryButton.snp.makeConstraints { $0.height.equalTo(46) }
progressView.snp.makeConstraints { $0.height.equalTo(3).priority(999) }
activity.snp.makeConstraints {
$0.centerY.equalToSuperview()
$0.centerX.equalToSuperview()
$0.size.equalTo(18)
}
}
/// 由当前页面状态显式刷新底栏,始终保留禁用按钮的可读标题。
/// 按产品页面的状态布局刷新底栏,忙碌按钮保持蓝色但不可重复触发。
func configure(title: String, detail: String?, primaryTitle: String, primaryEnabled: Bool,
secondaryTitle: String? = nil, progress: Float? = nil) {
secondaryTitle: String? = nil, progress: Float? = nil,
layout: Layout = .selection, isBusy: Bool = false) {
UIView.performWithoutAnimation {
if currentLayout != layout || hasSecondaryAction != (secondaryTitle != nil) {
arrange(layout, hasSecondary: secondaryTitle != nil)
}
titleLabel.attributedText = nil
titleLabel.text = title
if layout == .selection, let range = title.range(of: #"\d+"#, options: .regularExpression) {
let attributed = NSMutableAttributedString(string: title)
attributed.addAttributes([.foregroundColor: ScenicMaterialsStyle.primary,
.font: UIFont.systemFont(ofSize: 20, weight: .bold)],
range: NSRange(range, in: title))
titleLabel.attributedText = attributed
}
detailLabel.text = detail
detailLabel.isHidden = detail == nil
if primaryButton.title(for: .normal) != primaryTitle {
primaryButton.setTitle(primaryTitle, for: .normal)
primaryButton.setTitle(primaryTitle, for: .disabled)
}
primaryButton.backgroundColor = primaryEnabled ? ScenicMaterialsStyle.primary : ScenicMaterialsStyle.primary.withAlphaComponent(0.25)
detailLabel.isHidden = detail == nil || layout == .progress
primaryButton.accessibilityHint = detail
primaryButton.setTitle(primaryTitle, for: .normal)
primaryButton.setTitle(primaryTitle, for: .disabled)
let titleFont = primaryButton.titleLabel?.font ?? .systemFont(ofSize: 15, weight: .semibold)
let titleWidth = ceil(primaryTitle.size(withAttributes: [.font: titleFont]).width) + 2
activity.snp.updateConstraints { $0.centerX.equalToSuperview().offset(-titleWidth / 2 - 4) }
primaryButton.backgroundColor = primaryEnabled || isBusy ? ScenicMaterialsStyle.primary : UIColor(hex: 0xCDDFFF)
primaryButton.isEnabled = primaryEnabled
if secondaryButton.title(for: .normal) != secondaryTitle {
secondaryButton.setTitle(secondaryTitle, for: .normal)
}
secondaryButton.setTitle(secondaryTitle, for: .normal)
secondaryButton.isHidden = secondaryTitle == nil
secondaryButton.isEnabled = secondaryTitle != nil
progressView.isHidden = progress == nil
progressView.progress = min(max(progress ?? 0, 0), 1)
if isBusy { activity.startAnimating() } else { activity.stopAnimating() }
layoutIfNeeded()
}
}
@objc private func primaryTapped() { onPrimaryTap?() }
@objc private func secondaryTapped() { onSecondaryTap?() }
private func arrange(_ layout: Layout, hasSecondary: Bool) {
for container in [stack, summaryRow, actionRow] {
container.arrangedSubviews.forEach { container.removeArrangedSubview($0); $0.removeFromSuperview() }
}
titleLabel.snp.removeConstraints()
detailLabel.snp.removeConstraints()
secondaryButton.snp.removeConstraints()
actionRow.distribution = .fill
titleLabel.font = .systemFont(ofSize: layout == .selection ? 17 : 12)
detailLabel.textAlignment = layout == .selection ? .left : .right
secondaryButton.backgroundColor = layout == .result ? UIColor(hex: 0xF2F4F7) : .clear
secondaryButton.titleLabel?.font = .systemFont(ofSize: layout == .progress ? 12 : 15)
switch layout {
case .selection:
actionRow.addArrangedSubview(titleLabel)
actionRow.addArrangedSubview(primaryButton)
titleLabel.snp.makeConstraints { $0.width.equalTo(126).priority(999) }
stack.addArrangedSubview(actionRow)
stack.addArrangedSubview(detailLabel)
case .progress:
summaryRow.addArrangedSubview(titleLabel)
if hasSecondary {
summaryRow.addArrangedSubview(secondaryButton)
secondaryButton.snp.makeConstraints { $0.width.equalTo(44); $0.height.equalTo(28) }
}
actionRow.addArrangedSubview(primaryButton)
stack.addArrangedSubview(summaryRow)
stack.addArrangedSubview(progressView)
stack.addArrangedSubview(actionRow)
case .result:
summaryRow.addArrangedSubview(titleLabel)
summaryRow.addArrangedSubview(detailLabel)
titleLabel.setContentCompressionResistancePriority(.defaultHigh, for: .horizontal)
detailLabel.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
if hasSecondary {
actionRow.addArrangedSubview(secondaryButton)
secondaryButton.snp.makeConstraints { $0.height.equalTo(46) }
actionRow.distribution = .fillEqually
}
actionRow.addArrangedSubview(primaryButton)
stack.addArrangedSubview(summaryRow)
stack.addArrangedSubview(actionRow)
}
currentLayout = layout
hasSecondaryAction = hasSecondary
}
@objc private func primaryTapped() {
guard primaryButton.isEnabled else { return }
onPrimaryTap?()
}
@objc private func secondaryTapped() {
guard secondaryButton.isEnabled, !secondaryButton.isHidden else { return }
onSecondaryTap?()
}
}
@@ -29,35 +29,31 @@ final class ScenicMaterialRouteFilterViewController: UIViewController, UITableVi
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
let desiredHeight = min(CGFloat(routes.count + 1) * 58 + 90, 460)
let desiredHeight = min(CGFloat(routes.count + 1) * 50 + 100, 460)
sheetPresentationController?.detents = [.custom { min($0.maximumDetentValue, desiredHeight) }]
sheetPresentationController?.prefersGrabberVisible = true
sheetPresentationController?.preferredCornerRadius = 24
sheetPresentationController?.preferredCornerRadius = 22
}
private func setupUI() {
view.backgroundColor = .white
view.accessibilityIdentifier = "scenic.materials.route.sheet"
let title = ScenicMaterialsStyle.label("选择航线", size: 19, weight: .semibold)
let close = UIButton(type: .system)
close.setImage(UIImage(systemName: "xmark"), for: .normal)
close.tintColor = ScenicMaterialsStyle.secondary
close.accessibilityLabel = "关闭航线筛选"
close.accessibilityIdentifier = "scenic.materials.route.close"
close.addTarget(self, action: #selector(closeTapped), for: .touchUpInside)
let title = ScenicMaterialsStyle.label("选择航线", size: 18, weight: .semibold)
tableView.backgroundColor = .white
tableView.separatorStyle = .none
tableView.rowHeight = 58
tableView.separatorStyle = .singleLine
tableView.separatorColor = ScenicMaterialsStyle.border
tableView.separatorInset = .zero
tableView.tableFooterView = UIView()
tableView.rowHeight = 50
tableView.delegate = self
tableView.accessibilityIdentifier = "scenic.materials.route.list"
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "route")
[title, close, tableView].forEach(view.addSubview)
title.snp.makeConstraints { $0.top.equalTo(view.safeAreaLayoutGuide).offset(20); $0.leading.equalToSuperview().offset(22) }
close.snp.makeConstraints { $0.trailing.equalToSuperview().inset(10); $0.centerY.equalTo(title); $0.size.equalTo(44) }
[title, tableView].forEach(view.addSubview)
title.snp.makeConstraints { $0.top.equalTo(view.safeAreaLayoutGuide).offset(22); $0.leading.equalToSuperview().offset(18) }
tableView.snp.makeConstraints {
$0.top.equalTo(title.snp.bottom).offset(14)
$0.leading.trailing.equalToSuperview().inset(8)
$0.bottom.equalTo(view.safeAreaLayoutGuide)
$0.top.equalTo(title.snp.bottom).offset(12)
$0.leading.trailing.equalToSuperview().inset(22)
$0.bottom.equalTo(view.safeAreaLayoutGuide).inset(10)
}
dataSource = UITableViewDiffableDataSource<Int, Row>(tableView: tableView) { [weak self] table, indexPath, row in
guard let self else { return nil }
@@ -71,15 +67,27 @@ final class ScenicMaterialRouteFilterViewController: UIViewController, UITableVi
name = self.routes.first { $0.id == routeID }?.name ?? "航线暂不可用"
}
let selected = id == self.selectedRouteID
cell.textLabel?.text = name
cell.textLabel?.font = .systemFont(ofSize: 15, weight: selected ? .medium : .regular)
cell.textLabel?.textColor = selected ? ScenicMaterialsStyle.primary : ScenicMaterialsStyle.text
var configuration = cell.defaultContentConfiguration()
configuration.text = name
configuration.textProperties.font = .systemFont(ofSize: 14, weight: selected ? .medium : .regular)
configuration.textProperties.color = selected ? ScenicMaterialsStyle.primary : ScenicMaterialsStyle.text
configuration.directionalLayoutMargins = .zero
cell.contentConfiguration = configuration
cell.backgroundColor = .white
let image = UIImageView(image: UIImage(systemName: selected ? "checkmark.circle.fill" : "circle",
withConfiguration: UIImage.SymbolConfiguration(pointSize: 22)))
image.tintColor = selected ? ScenicMaterialsStyle.primary : ScenicMaterialsStyle.border
image.frame = CGRect(x: 0, y: 0, width: 24, height: 24)
cell.accessoryView = image
cell.selectionStyle = .none
cell.layoutMargins = .zero
cell.preservesSuperviewLayoutMargins = false
cell.separatorInset = .zero
if selected {
let image = UIImageView(image: UIImage(systemName: "checkmark",
withConfiguration: UIImage.SymbolConfiguration(pointSize: 16, weight: .medium)))
image.tintColor = ScenicMaterialsStyle.primary
image.frame = CGRect(x: 0, y: 0, width: 20, height: 20)
cell.accessoryView = image
} else {
cell.accessoryView = nil
}
cell.accessibilityLabel = name
cell.accessibilityIdentifier = "scenic.materials.route.\(id ?? "all")"
cell.accessibilityTraits = selected ? [.button, .selected] : .button
return cell
@@ -99,19 +107,17 @@ final class ScenicMaterialRouteFilterViewController: UIViewController, UITableVi
dismiss(animated: true) { completion?(id) }
}
@objc private func closeTapped() { dismiss(animated: true) }
}
/// 景区素材起止日期筛选 Sheet,临时选择只在点击确定后应用。
@MainActor
final class ScenicMaterialDateFilterViewController: UIViewController {
final class ScenicMaterialDateFilterViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate {
/// nil/nil 表示保留期内的全部时间,其他值为按日包含端点的区间。
var onSelectRange: ((Date?, Date?) -> Void)?
/// 当前正在编辑的日期端点。
private enum Endpoint: Equatable { case start, end }
private let minimumDate: Date
private let maximumDate: Date
private let dateOptions: ScenicMaterialDatePickerOptions
private let calendar: Calendar
private var startDate: Date
private var endDate: Date
@@ -120,18 +126,19 @@ final class ScenicMaterialDateFilterViewController: UIViewController {
private let allButton = UIButton(type: .system)
private let startButton = UIButton(type: .custom)
private let endButton = UIButton(type: .custom)
private let picker = UIDatePicker()
private let picker = UIPickerView()
/// 约束到服务端约定或演示给定的保留区间,不提供未来日期。
init(start: Date?, end: Date?, minimumDate: Date, maximumDate: Date, calendar: Calendar = .current) {
self.calendar = calendar
self.minimumDate = calendar.startOfDay(for: minimumDate)
self.maximumDate = max(calendar.startOfDay(for: minimumDate), calendar.startOfDay(for: maximumDate))
let clampedStart = min(max(calendar.startOfDay(for: start ?? maximumDate), self.minimumDate), self.maximumDate)
let clampedEnd = min(max(calendar.startOfDay(for: end ?? maximumDate), self.minimumDate), self.maximumDate)
let options = ScenicMaterialDatePickerOptions(minimumDate: minimumDate, maximumDate: maximumDate, calendar: calendar)
dateOptions = options
let clampedStart = options.clamped(start ?? maximumDate)
let clampedEnd = options.clamped(end ?? maximumDate)
self.startDate = min(clampedStart, clampedEnd)
self.endDate = max(clampedStart, clampedEnd)
usesAllDates = start == nil && end == nil
// 打开面板先编辑日期草稿;取消不会改变列表当前的“全部时间”。
usesAllDates = false
super.init(nibName: nil, bundle: nil)
modalPresentationStyle = .pageSheet
}
@@ -143,15 +150,15 @@ final class ScenicMaterialDateFilterViewController: UIViewController {
super.viewDidLoad()
setupUI()
updateUI()
sheetPresentationController?.detents = [.custom { min($0.maximumDetentValue, 530) }]
sheetPresentationController?.detents = [.custom { min($0.maximumDetentValue, 531) }]
sheetPresentationController?.prefersGrabberVisible = true
sheetPresentationController?.preferredCornerRadius = 24
sheetPresentationController?.preferredCornerRadius = 22
}
private func setupUI() {
view.backgroundColor = .white
view.accessibilityIdentifier = "scenic.materials.date.sheet"
let title = ScenicMaterialsStyle.label("选择时间", size: 19, weight: .semibold)
let title = ScenicMaterialsStyle.label("选择时间", size: 18, weight: .semibold)
let hint = ScenicMaterialsStyle.label("选择起止日期", size: 13, color: ScenicMaterialsStyle.secondary)
allButton.addTarget(self, action: #selector(allTapped), for: .touchUpInside)
allButton.accessibilityIdentifier = "scenic.materials.date.all"
@@ -166,19 +173,14 @@ final class ScenicMaterialDateFilterViewController: UIViewController {
let dateRow = UIStackView(arrangedSubviews: [startButton, endButton])
dateRow.distribution = .fillEqually
dateRow.spacing = 12
picker.datePickerMode = .date
picker.preferredDatePickerStyle = .wheels
picker.locale = Locale(identifier: "zh_CN")
picker.calendar = calendar
picker.timeZone = calendar.timeZone
picker.minimumDate = minimumDate
picker.maximumDate = maximumDate
picker.dataSource = self
picker.delegate = self
picker.accessibilityIdentifier = "scenic.materials.date.picker"
picker.addTarget(self, action: #selector(dateChanged), for: .valueChanged)
let retention = ScenicMaterialsStyle.label("仅显示保留期内已到来的日期", size: 11, color: ScenicMaterialsStyle.secondary)
retention.textAlignment = .center
let cancel = UIButton(type: .system)
cancel.setTitle("取消", for: .normal)
cancel.titleLabel?.font = .systemFont(ofSize: 15, weight: .medium)
cancel.tintColor = ScenicMaterialsStyle.secondary
cancel.backgroundColor = UIColor(hex: 0xF5F6F8)
cancel.layer.cornerRadius = 10
@@ -186,6 +188,7 @@ final class ScenicMaterialDateFilterViewController: UIViewController {
cancel.addTarget(self, action: #selector(cancelTapped), for: .touchUpInside)
let confirm = UIButton(type: .system)
confirm.setTitle("确定", for: .normal)
confirm.titleLabel?.font = .systemFont(ofSize: 15, weight: .semibold)
confirm.setTitleColor(.white, for: .normal)
confirm.backgroundColor = ScenicMaterialsStyle.primary
confirm.layer.cornerRadius = 10
@@ -201,7 +204,7 @@ final class ScenicMaterialDateFilterViewController: UIViewController {
scrollView.addSubview(content)
[title, hint, allButton, dateRow, picker, retention].forEach(content.addSubview)
actions.snp.makeConstraints {
$0.leading.trailing.equalToSuperview().inset(22)
$0.leading.trailing.equalToSuperview().inset(18)
$0.bottom.equalTo(view.safeAreaLayoutGuide).inset(12)
$0.height.equalTo(46)
}
@@ -210,21 +213,19 @@ final class ScenicMaterialDateFilterViewController: UIViewController {
$0.bottom.equalTo(actions.snp.top).offset(-12)
}
content.snp.makeConstraints { $0.edges.equalTo(scrollView.contentLayoutGuide); $0.width.equalTo(scrollView.frameLayoutGuide) }
title.snp.makeConstraints { $0.top.equalToSuperview().offset(20); $0.leading.equalToSuperview().offset(22) }
hint.snp.makeConstraints { $0.top.equalTo(title.snp.bottom).offset(12); $0.leading.equalTo(title) }
allButton.snp.makeConstraints { $0.centerY.equalTo(hint); $0.trailing.equalToSuperview().inset(22); $0.height.equalTo(44) }
dateRow.snp.makeConstraints { $0.top.equalTo(hint.snp.bottom).offset(16); $0.leading.trailing.equalToSuperview().inset(22); $0.height.equalTo(65) }
picker.snp.makeConstraints { $0.top.equalTo(dateRow.snp.bottom).offset(4); $0.leading.trailing.equalToSuperview().inset(12); $0.height.equalTo(210) }
retention.snp.makeConstraints { $0.top.equalTo(picker.snp.bottom).offset(4); $0.leading.trailing.equalToSuperview().inset(20); $0.bottom.equalToSuperview().inset(4) }
title.snp.makeConstraints { $0.top.equalToSuperview().offset(24); $0.leading.equalToSuperview().offset(18) }
hint.snp.makeConstraints { $0.top.equalTo(title.snp.bottom).offset(22); $0.leading.equalTo(title) }
allButton.snp.makeConstraints { $0.centerY.equalTo(hint); $0.trailing.equalToSuperview().inset(18); $0.height.equalTo(36) }
dateRow.snp.makeConstraints { $0.top.equalTo(hint.snp.bottom).offset(20); $0.leading.trailing.equalToSuperview().inset(18); $0.height.equalTo(72) }
picker.snp.makeConstraints { $0.top.equalTo(dateRow.snp.bottom).offset(10); $0.leading.trailing.equalToSuperview().inset(18); $0.height.equalTo(200) }
retention.snp.makeConstraints { $0.top.equalTo(picker.snp.bottom).offset(12); $0.leading.trailing.equalToSuperview().inset(18); $0.bottom.equalToSuperview().inset(4) }
}
private func updateUI() {
var allConfiguration = UIButton.Configuration.plain()
allConfiguration.title = "全部时间"
allConfiguration.image = UIImage(systemName: usesAllDates ? "checkmark.circle.fill" : "circle")
allConfiguration.imagePadding = 5
allConfiguration.baseForegroundColor = usesAllDates ? ScenicMaterialsStyle.primary : ScenicMaterialsStyle.secondary
allConfiguration.preferredSymbolConfigurationForImage = UIImage.SymbolConfiguration(pointSize: 16)
allConfiguration.baseForegroundColor = ScenicMaterialsStyle.primary
allConfiguration.contentInsets = .zero
allConfiguration.titleTextAttributesTransformer = UIConfigurationTextAttributesTransformer { input in
var output = input; output.font = .systemFont(ofSize: 12); return output
}
@@ -234,11 +235,11 @@ final class ScenicMaterialDateFilterViewController: UIViewController {
formatter.calendar = calendar
formatter.timeZone = calendar.timeZone
formatter.locale = Locale(identifier: "zh_CN")
formatter.dateFormat = "M 月 d 日"
formatter.dateFormat = "M月d日"
for (button, value, name, candidate) in [(startButton, startDate, "开始日期", Endpoint.start), (endButton, endDate, "结束日期", Endpoint.end)] {
let active = endpoint == candidate && !usesAllDates
let foreground = active ? ScenicMaterialsStyle.primary : ScenicMaterialsStyle.text
let titleColor = active ? ScenicMaterialsStyle.primary : ScenicMaterialsStyle.secondary
let titleColor = ScenicMaterialsStyle.secondary
var configuration = UIButton.Configuration.plain()
configuration.title = name
configuration.subtitle = formatter.string(from: value)
@@ -254,7 +255,7 @@ final class ScenicMaterialDateFilterViewController: UIViewController {
}
configuration.subtitleTextAttributesTransformer = UIConfigurationTextAttributesTransformer { attributes in
var result = attributes
result.font = .systemFont(ofSize: 14, weight: active ? .medium : .regular)
result.font = .systemFont(ofSize: 18, weight: .semibold)
result.foregroundColor = foreground
return result
}
@@ -263,11 +264,17 @@ final class ScenicMaterialDateFilterViewController: UIViewController {
button.layoutIfNeeded()
}
button.backgroundColor = active ? ScenicMaterialsStyle.primary.withAlphaComponent(0.06) : UIColor(hex: 0xF7F8FA)
button.layer.borderColor = (active ? ScenicMaterialsStyle.primary : ScenicMaterialsStyle.border).cgColor
button.layer.borderColor = (active ? ScenicMaterialsStyle.primary.withAlphaComponent(0.35) : ScenicMaterialsStyle.border).cgColor
button.accessibilityTraits = active ? [.button, .selected] : .button
button.accessibilityLabel = "\(name),\(formatter.string(from: value))"
}
picker.setDate(endpoint == .start ? startDate : endDate, animated: false)
let value = endpoint == .start ? startDate : endDate
let monthIndex = dateOptions.monthIndex(for: value)
picker.selectRow(monthIndex, inComponent: 0, animated: false)
picker.reloadComponent(1)
let dayIndex = dateOptions.months[monthIndex].dates.firstIndex(of: value) ?? 0
picker.selectRow(dayIndex, inComponent: 1, animated: false)
picker.accessibilityLabel = endpoint == .start ? "开始日期,月份和日期" : "结束日期,月份和日期"
picker.alpha = usesAllDates ? 0.4 : 1
picker.isUserInteractionEnabled = !usesAllDates
}
@@ -276,8 +283,50 @@ final class ScenicMaterialDateFilterViewController: UIViewController {
@objc private func startTapped() { endpoint = .start; usesAllDates = false; updateUI() }
@objc private func endTapped() { endpoint = .end; usesAllDates = false; updateUI() }
@objc private func dateChanged() {
let value = min(max(calendar.startOfDay(for: picker.date), minimumDate), maximumDate)
/// 两列分别表示保留期内的月份与所选月份内的日号。
func numberOfComponents(in pickerView: UIPickerView) -> Int { 2 }
/// 首尾月份按保留期裁剪,滚轮中不会出现不可提交的日期。
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
if component == 0 { return dateOptions.months.count }
return dateOptions.months[max(pickerView.selectedRow(inComponent: 0), 0)].dates.count
}
/// 使用与网页一致的 40 点行高。
func pickerView(_ pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat { 40 }
/// 月份和日期占据等宽两列。
func pickerView(_ pickerView: UIPickerView, widthForComponent component: Int) -> CGFloat { pickerView.bounds.width / 2 }
/// 日期文案不显示年份列,辅助功能仍包含月份的年份。
func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {
let label = (view as? UILabel) ?? UILabel()
label.font = .systemFont(ofSize: 20, weight: .medium)
label.textColor = ScenicMaterialsStyle.text
label.textAlignment = .center
if component == 0 {
let month = dateOptions.months[row]
label.text = dateOptions.monthTitle(at: row)
label.accessibilityLabel = "\(month.year)年\(month.number)月"
} else {
let month = dateOptions.months[max(pickerView.selectedRow(inComponent: 0), 0)]
label.text = "\(calendar.component(.day, from: month.dates[row]))日"
label.accessibilityLabel = label.text
}
return label
}
/// 更改月份时保留日号并收敛月末;更改端点后同步修正倒置区间。
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
usesAllDates = false
let monthIndex = max(pickerView.selectedRow(inComponent: 0), 0)
let value: Date
if component == 0 {
let current = endpoint == .start ? startDate : endDate
value = dateOptions.date(inMonthAt: row, preferredDay: calendar.component(.day, from: current))
} else {
value = dateOptions.months[monthIndex].dates[row]
}
if endpoint == .start {
startDate = value
if endDate < value { endDate = value }
@@ -1,9 +1,10 @@
import Kingfisher
import AVFoundation
import AVKit
import SnapKit
import UIKit
/// 景区空镜独立预览面板,仅播放应用内演示短片,不接入订单或网络素材。
/// 景区空境视频预览,正式素材播放服务端地址,Debug 素材保留本地预览。
@MainActor
final class ScenicMaterialPreviewViewController: UIViewController {
private let clip: ScenicMaterialClip
@@ -11,10 +12,17 @@ final class ScenicMaterialPreviewViewController: UIViewController {
private let capturedAt: Date
private let calendar: Calendar
private let playerController = AVPlayerViewController()
private let contentView = UIView()
private let coverView = UIImageView()
private let playButton = UIButton(type: .system)
private let playbackStatus = ScenicMaterialsStyle.label("本地演示短片 · 非真实景区视频", size: 11, color: ScenicMaterialsStyle.secondary)
private let playbackStatus = ScenicMaterialsStyle.label(size: 13, color: ScenicMaterialsStyle.secondary)
private let playbackTime = ScenicMaterialsStyle.label(size: 11, color: ScenicMaterialsStyle.secondary)
private let progressView = UIProgressView(progressViewStyle: .bar)
private var playbackTask: Task<Void, Never>?
private var playbackObservation: ScenicMaterialPlaybackObservation?
private var playbackGeneration = UUID()
private var playbackDuration: Double?
private var playbackFinished = false
/// 预览指定片段,原片元信息与本地演示视频时长明确区分。
init(clip: ScenicMaterialClip, routeName: String, capturedAt: Date, calendar: Calendar = .current) {
@@ -32,9 +40,16 @@ final class ScenicMaterialPreviewViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
sheetPresentationController?.detents = [.custom { min($0.maximumDetentValue, 510) }]
sheetPresentationController?.detents = [.custom { [weak self] context in
guard let self else { return min(context.maximumDetentValue, 490) }
let width = max(self.view.bounds.width, 320)
let fittingSize = self.contentView.systemLayoutSizeFitting(
CGSize(width: width, height: UIView.layoutFittingCompressedSize.height),
withHorizontalFittingPriority: .required, verticalFittingPriority: .fittingSizeLevel)
return min(context.maximumDetentValue, fittingSize.height)
}]
sheetPresentationController?.prefersGrabberVisible = true
sheetPresentationController?.preferredCornerRadius = 24
sheetPresentationController?.preferredCornerRadius = 22
NotificationCenter.default.addObserver(self, selector: #selector(pausePlayback),
name: UIApplication.willResignActiveNotification, object: nil)
}
@@ -42,37 +57,51 @@ final class ScenicMaterialPreviewViewController: UIViewController {
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
pausePlayback()
playbackTask?.cancel()
playbackTask = nil
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
stopPlayback()
}
private func setupUI() {
view.backgroundColor = .white
view.accessibilityIdentifier = "scenic.materials.preview.sheet"
let title = ScenicMaterialsStyle.label("视频预览", size: 19, weight: .semibold)
let closeButton = UIButton(type: .system)
closeButton.setImage(UIImage(systemName: "xmark"), for: .normal)
closeButton.tintColor = ScenicMaterialsStyle.secondary
closeButton.accessibilityLabel = "关闭景区视频预览"
closeButton.accessibilityIdentifier = "scenic.materials.preview.close"
closeButton.addTarget(self, action: #selector(closeTapped), for: .touchUpInside)
let title = ScenicMaterialsStyle.label("视频预览", size: 18, weight: .semibold)
let mediaContainer = UIView()
mediaContainer.backgroundColor = .black
mediaContainer.layer.cornerRadius = 12
mediaContainer.layer.cornerRadius = 10
mediaContainer.clipsToBounds = true
coverView.image = UIImage(named: clip.coverAssetName)
mediaContainer.accessibilityIdentifier = "scenic.materials.preview.media"
if clip.isRemote {
coverView.kf.setImage(with: clip.coverURL, placeholder: UIImage(systemName: "photo"))
playbackStatus.text = "点击播放原片"
} else {
coverView.image = UIImage(named: clip.coverAssetName)
playbackStatus.text = "本地演示短片 · 非真实景区视频"
}
coverView.contentMode = .scaleAspectFill
coverView.clipsToBounds = true
playButton.setImage(UIImage(systemName: "play.circle.fill", withConfiguration: UIImage.SymbolConfiguration(pointSize: 48)), for: .normal)
playButton.tintColor = .white
playButton.accessibilityLabel = "播放本地演示视频"
playButton.accessibilityIdentifier = "scenic.materials.preview.play"
playButton.addTarget(self, action: #selector(playTapped), for: .touchUpInside)
updatePlayButton(isPlaying: false)
playbackStatus.numberOfLines = 2
let metadata = ScenicMaterialsStyle.label("片段 \(String(format: "%02d", clip.ordinal)) · 原片 \(clip.durationText) · \(clip.resolution) · \(clip.sizeText)", size: 12, color: ScenicMaterialsStyle.secondary)
progressView.progressTintColor = ScenicMaterialsStyle.primary
progressView.trackTintColor = ScenicMaterialsStyle.border
progressView.accessibilityIdentifier = "scenic.materials.preview.progress"
progressView.accessibilityLabel = "播放进度"
playbackTime.accessibilityIdentifier = "scenic.materials.preview.playbackTime"
resetPlaybackTime()
let metadata = ScenicMaterialsStyle.label("\(clip.resolution) · \(clip.sizeText)", size: 11, color: ScenicMaterialsStyle.secondary)
metadata.numberOfLines = 2
metadata.textAlignment = .right
metadata.accessibilityIdentifier = "scenic.materials.preview.metadata"
let route = ScenicMaterialsStyle.label(routeName, size: 17, weight: .semibold)
let timeline = UIStackView(arrangedSubviews: [playbackTime, metadata])
timeline.alignment = .top
timeline.distribution = .fillEqually
timeline.spacing = 8
let route = ScenicMaterialsStyle.label(routeName, size: 16, weight: .semibold)
route.numberOfLines = 2
route.accessibilityIdentifier = "scenic.materials.preview.route"
let formatter = DateFormatter()
@@ -80,80 +109,192 @@ final class ScenicMaterialPreviewViewController: UIViewController {
formatter.timeZone = calendar.timeZone
formatter.locale = Locale(identifier: "zh_CN")
formatter.dateFormat = "MM-dd HH:mm"
let time = ScenicMaterialsStyle.label(formatter.string(from: capturedAt), size: 12, color: ScenicMaterialsStyle.secondary)
let time = ScenicMaterialsStyle.label("\(formatter.string(from: capturedAt)) · 片段 \(clip.ordinal)", size: 12, color: ScenicMaterialsStyle.secondary)
time.accessibilityIdentifier = "scenic.materials.preview.capturedAt"
let done = UIButton(type: .system)
done.setTitle("返回素材列表", for: .normal)
done.setTitleColor(ScenicMaterialsStyle.primary, for: .normal)
done.titleLabel?.font = .systemFont(ofSize: 14, weight: .medium)
done.backgroundColor = ScenicMaterialsStyle.primary.withAlphaComponent(0.07)
done.setTitleColor(.white, for: .normal)
done.titleLabel?.font = .systemFont(ofSize: 15, weight: .semibold)
done.backgroundColor = ScenicMaterialsStyle.primary
done.layer.cornerRadius = 10
done.accessibilityIdentifier = "scenic.materials.preview.done"
done.addTarget(self, action: #selector(closeTapped), for: .touchUpInside)
let scroll = UIScrollView()
let content = UIView()
view.addSubview(scroll)
scroll.addSubview(content)
[title, closeButton, playbackStatus, mediaContainer, metadata, route, time, done].forEach(content.addSubview)
scroll.addSubview(contentView)
[title, playbackStatus, mediaContainer, progressView, timeline, route, time, done].forEach(contentView.addSubview)
addChild(playerController)
playerController.view.backgroundColor = .black
playerController.view.isHidden = true
playerController.showsPlaybackControls = false
playerController.allowsPictureInPicturePlayback = false
playerController.exitsFullScreenWhenPlaybackEnds = true
mediaContainer.addSubview(playerController.view)
playerController.didMove(toParent: self)
mediaContainer.addSubview(coverView)
mediaContainer.addSubview(playButton)
scroll.snp.makeConstraints { $0.edges.equalTo(view.safeAreaLayoutGuide) }
content.snp.makeConstraints { $0.edges.equalTo(scroll.contentLayoutGuide); $0.width.equalTo(scroll.frameLayoutGuide) }
title.snp.makeConstraints { $0.top.equalToSuperview().offset(20); $0.leading.equalToSuperview().offset(22) }
closeButton.snp.makeConstraints { $0.trailing.equalToSuperview().inset(10); $0.centerY.equalTo(title); $0.size.equalTo(44) }
playbackStatus.snp.makeConstraints { $0.top.equalTo(title.snp.bottom).offset(10); $0.leading.trailing.equalToSuperview().inset(22) }
contentView.snp.makeConstraints { $0.edges.equalTo(scroll.contentLayoutGuide); $0.width.equalTo(scroll.frameLayoutGuide) }
title.snp.makeConstraints { $0.top.equalToSuperview().offset(24); $0.leading.trailing.equalToSuperview().inset(18) }
playbackStatus.snp.makeConstraints { $0.top.equalTo(title.snp.bottom).offset(6); $0.leading.trailing.equalTo(title) }
mediaContainer.snp.makeConstraints {
$0.top.equalTo(playbackStatus.snp.bottom).offset(14)
$0.leading.trailing.equalToSuperview().inset(22)
$0.top.equalTo(playbackStatus.snp.bottom).offset(18)
$0.leading.trailing.equalTo(title)
$0.height.equalTo(mediaContainer.snp.width).multipliedBy(9.0 / 16.0)
}
playerController.view.snp.makeConstraints { $0.edges.equalToSuperview() }
coverView.snp.makeConstraints { $0.edges.equalToSuperview() }
playButton.snp.makeConstraints { $0.edges.equalToSuperview() }
metadata.snp.makeConstraints { $0.top.equalTo(mediaContainer.snp.bottom).offset(10); $0.leading.trailing.equalTo(mediaContainer) }
route.snp.makeConstraints { $0.top.equalTo(metadata.snp.bottom).offset(17); $0.leading.trailing.equalTo(mediaContainer) }
time.snp.makeConstraints { $0.top.equalTo(route.snp.bottom).offset(8); $0.leading.trailing.equalTo(mediaContainer) }
playButton.snp.makeConstraints { $0.center.equalToSuperview(); $0.size.equalTo(44) }
progressView.snp.makeConstraints { $0.top.equalTo(mediaContainer.snp.bottom).offset(16); $0.leading.trailing.equalTo(mediaContainer); $0.height.equalTo(3) }
timeline.snp.makeConstraints { $0.top.equalTo(progressView.snp.bottom).offset(8); $0.leading.trailing.equalTo(mediaContainer) }
route.snp.makeConstraints { $0.top.equalTo(timeline.snp.bottom).offset(22); $0.leading.trailing.equalTo(mediaContainer) }
time.snp.makeConstraints { $0.top.equalTo(route.snp.bottom).offset(7); $0.leading.trailing.equalTo(mediaContainer) }
done.snp.makeConstraints {
$0.top.equalTo(time.snp.bottom).offset(18)
$0.top.equalTo(time.snp.bottom).offset(20)
$0.leading.trailing.equalTo(mediaContainer)
$0.height.equalTo(44)
$0.bottom.equalToSuperview().inset(14)
$0.height.equalTo(46)
$0.bottom.equalToSuperview().inset(18)
}
}
@objc private func playTapped() {
guard playbackTask == nil, clip.isAvailable else { return }
guard let url = Bundle.main.url(forResource: "drone_material_demo", withExtension: "mp4")
?? Bundle.main.url(forResource: "drone_material_demo", withExtension: "mp4", subdirectory: "DroneDock") else {
playbackStatus.text = "本地演示视频暂不可用"
if let player = playerController.player {
if player.rate > 0 {
pausePlayback()
} else {
if playbackFinished { player.seek(to: .zero); playbackFinished = false }
player.play()
updatePlayButton(isPlaying: true)
updatePlayingStatus()
}
return
}
let demoURL = Bundle.main.url(forResource: "drone_material_demo", withExtension: "mp4")
?? Bundle.main.url(forResource: "drone_material_demo", withExtension: "mp4", subdirectory: "DroneDock")
guard let url = clip.isRemote ? clip.remoteURL : demoURL else {
playbackStatus.text = "视频地址暂不可用"
return
}
playButton.isEnabled = false
playbackGeneration = UUID()
let generation = playbackGeneration
playbackTask = Task { @MainActor [weak self] in
let playable = (try? await AVURLAsset(url: url).load(.isPlayable)) == true
guard let self else { return }
let asset = AVURLAsset(url: url)
let playable = (try? await asset.load(.isPlayable)) == true
let duration = try? await asset.load(.duration)
guard let self, self.playbackGeneration == generation else { return }
self.playbackTask = nil
self.playButton.isEnabled = true
guard !Task.isCancelled, self.view.window != nil else { return }
guard playable else {
self.playbackStatus.text = "本地演示视频暂不可播放"
self.playbackStatus.text = "视频暂不可播放,请稍后重试"
return
}
self.playerController.player = AVPlayer(url: url)
let seconds = duration?.seconds ?? .nan
self.playbackDuration = seconds.isFinite && seconds > 0 ? seconds : nil
let player = AVPlayer(playerItem: AVPlayerItem(asset: asset))
self.playerController.player = player
self.playerController.view.isHidden = false
self.coverView.isHidden = true
self.playButton.isHidden = true
self.playbackStatus.text = "正在播放 3 秒本地演示 · 原片时长见下方"
self.playerController.player?.play()
self.playbackFinished = false
self.playbackObservation = ScenicMaterialPlaybackObservation(player: player) { [weak self] time in
Task { @MainActor [weak self] in
guard let self, self.playbackGeneration == generation else { return }
self.updatePlaybackProgress(time)
}
}
NotificationCenter.default.addObserver(self, selector: #selector(playbackEnded),
name: .AVPlayerItemDidPlayToEndTime, object: player.currentItem)
self.updatePlaybackProgress(.zero)
self.updatePlayingStatus()
self.updatePlayButton(isPlaying: true)
player.play()
}
}
@objc private func pausePlayback() { playerController.player?.pause() }
@objc private func closeTapped() { pausePlayback(); dismiss(animated: true) }
private func updatePlaybackProgress(_ time: CMTime) {
let seconds = time.seconds.isFinite ? max(time.seconds, 0) : 0
progressView.progress = playbackDuration.map { Float(min(seconds / $0, 1)) } ?? 0
let total = playbackDuration.map(Self.durationText) ?? "时长未知"
playbackTime.text = "\(Self.durationText(seconds)) / \(total)"
}
private func updatePlayingStatus() {
if clip.isRemote {
playbackStatus.text = "正在播放原片"
} else if let duration = playbackDuration {
playbackStatus.text = "正在播放 \(Int(duration.rounded())) 秒本地演示 · 原片 \(clip.durationText)"
} else {
playbackStatus.text = "正在播放本地演示 · 原片 \(clip.durationText)"
}
}
private func updatePlayButton(isPlaying: Bool) {
let symbol = isPlaying ? "pause.fill" : "play.fill"
playButton.setImage(UIImage(systemName: symbol, withConfiguration: UIImage.SymbolConfiguration(pointSize: 24)), for: .normal)
playButton.accessibilityLabel = isPlaying ? "暂停播放" : (clip.isRemote ? "播放景区视频" : "播放本地演示视频")
}
private func resetPlaybackTime() {
playbackTime.text = "00:00 / \(clip.isRemote ? "" : "原片 ")\(clip.durationText)"
}
private static func durationText(_ seconds: Double) -> String {
let value = max(Int(seconds), 0)
return String(format: "%02d:%02d", value / 60, value % 60)
}
@objc private func playbackEnded() {
playbackFinished = true
if let duration = playbackDuration { updatePlaybackProgress(CMTime(seconds: duration, preferredTimescale: 600)) }
updatePlayButton(isPlaying: false)
playbackStatus.text = clip.isRemote ? "播放结束,点击重新播放" : "本地演示已结束 · 原片 \(clip.durationText)"
}
@objc private func pausePlayback() {
playerController.player?.pause()
if playbackTask != nil {
playbackGeneration = UUID()
playbackTask?.cancel()
playbackTask = nil
playButton.isEnabled = true
}
updatePlayButton(isPlaying: false)
if playerController.player != nil {
playbackStatus.text = clip.isRemote ? "已暂停,点击继续播放" : "本地演示已暂停 · 原片 \(clip.durationText)"
}
}
private func stopPlayback() {
pausePlayback()
playbackGeneration = UUID()
NotificationCenter.default.removeObserver(self, name: .AVPlayerItemDidPlayToEndTime, object: playerController.player?.currentItem)
playbackObservation = nil
playerController.player = nil
playerController.view.isHidden = true
coverView.isHidden = false
playbackDuration = nil
playbackFinished = false
progressView.progress = 0
resetPlaybackTime()
}
@objc private func closeTapped() {
stopPlayback()
dismiss(animated: true)
}
}
/// 与播放器成对持有周期观察令牌,释放时移除观察,避免弹窗销毁后残留定时回调。
private final class ScenicMaterialPlaybackObservation {
private let player: AVPlayer
private let token: Any
init(player: AVPlayer, onTime: @escaping @Sendable (CMTime) -> Void) {
self.player = player
token = player.addPeriodicTimeObserver(forInterval: CMTime(seconds: 0.1, preferredTimescale: 600),
queue: .main, using: onTime)
}
deinit { player.removeTimeObserver(token) }
}
@@ -1,3 +1,4 @@
import Photos
import SnapKit
import UIKit
@@ -21,6 +22,11 @@ final class ScenicMaterialsViewController: BaseViewController {
private let emptyMessage = ScenicMaterialsStyle.label(size: 14, color: ScenicMaterialsStyle.secondary)
private let resetButton = UIButton(type: .system)
private let driver = ScenicMaterialDemoDownloadDriver()
private let downloadService = ScenicMaterialDownloadService()
private var loadTask: Task<Void, Never>?
private let refreshControl = UIRefreshControl()
private let retryButton = UIButton(type: .system)
private var authorizationTask: Task<Void, Never>?
private lazy var collectionView = UICollectionView(frame: .zero, collectionViewLayout: makeLayout())
private var dataSource: UICollectionViewDiffableDataSource<Section, Item>!
private var isDemoPhotoPermissionAllowed: Bool
@@ -36,6 +42,36 @@ final class ScenicMaterialsViewController: BaseViewController {
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
override func viewDidLoad() {
super.viewDidLoad()
if viewModel.isRemote { reloadRemoteMaterials() }
}
@objc private func reloadRemoteMaterials() {
guard viewModel.isRemote, !viewModel.isSelectionLocked else { refreshControl.endRefreshing(); return }
loadTask?.cancel()
let session = AppStore.shared.session
guard session.accountType == .storeUser, session.userId == viewModel.context.userID,
String(session.currentScenicId) == viewModel.context.scenicID else {
refreshControl.endRefreshing()
showToast("请使用门店账号并重新进入当前景区素材库")
return
}
let api = ScenicMaterialsAPI(client: NetworkServices.shared.apiClient)
emptyTitle.text = "正在加载素材"
emptyMessage.text = "请稍候"
retryButton.isHidden = true
routeButton.isEnabled = false
dateButton.isEnabled = false
loadTask = Task { @MainActor [weak self] in
guard let self else { return }
await self.viewModel.loadRemoteSessions(api: api)
guard !Task.isCancelled else { return }
self.refreshControl.endRefreshing()
self.refreshDisplay()
}
}
override func setupNavigationBar() {
title = "景区空境库"
navigationItem.backButtonDisplayMode = .minimal
@@ -48,12 +84,14 @@ final class ScenicMaterialsViewController: BaseViewController {
navigationItem.standardAppearance = appearance
navigationItem.scrollEdgeAppearance = appearance
#if DEBUG
guard !viewModel.isRemote else { return }
var actions: [UIAction] = ScenicMaterialsScenario.allCases.map { scenario in
UIAction(title: scenario.title) { [weak self] _ in self?.applyPreviewScenario(scenario) }
}
actions.append(UIAction(title: "相册权限不足") { [weak self] _ in
guard let self else { return }
self.driver.stop()
self.downloadService.stop()
self.viewModel.pauseDownload()
self.isDemoPhotoPermissionAllowed = false
self.refreshDisplay(animated: false)
@@ -89,6 +127,10 @@ final class ScenicMaterialsViewController: BaseViewController {
view.addSubview(filterBar)
view.addSubview(collectionView)
view.addSubview(footer)
if viewModel.isRemote {
collectionView.refreshControl = refreshControl
refreshControl.addTarget(self, action: #selector(reloadRemoteMaterials), for: .valueChanged)
}
setupEmptyView()
configureDataSource()
refreshDisplay(animated: false)
@@ -98,7 +140,7 @@ final class ScenicMaterialsViewController: BaseViewController {
filterBar.snp.makeConstraints { make in
make.top.equalTo(view.safeAreaLayoutGuide).offset(10)
make.leading.trailing.equalToSuperview().inset(16)
make.height.equalTo(42)
make.height.equalTo(40)
}
collectionView.snp.makeConstraints { make in
make.top.equalTo(filterBar.snp.bottom).offset(8)
@@ -116,6 +158,7 @@ final class ScenicMaterialsViewController: BaseViewController {
footer.onSecondaryTap = { [weak self] in
guard let self else { return }
self.driver.stop()
self.downloadService.stop()
if self.viewModel.phase == .downloading || self.viewModel.phase == .paused {
self.viewModel.cancelDownload()
} else {
@@ -133,20 +176,30 @@ final class ScenicMaterialsViewController: BaseViewController {
guard isMovingFromParent || isBeingDismissed || navigationController?.isBeingDismissed == true else { return }
if let coordinator = transitionCoordinator, coordinator.isInteractive {
coordinator.animate(alongsideTransition: nil) { [weak self] context in
if !context.isCancelled { self?.pauseForBackground() }
if !context.isCancelled { self?.finishLeaving() }
}
} else {
pauseForBackground()
finishLeaving()
}
}
/// 仅在确认离开页面后作废异步工作,取消返回手势继续保留原来的加载及下载。
private func finishLeaving() {
loadTask?.cancel()
viewModel.cancelRemoteLoad()
authorizationTask?.cancel()
authorizationTask = nil
pauseForBackground()
}
/// 外部演示回执后显式刷新,不自动开始或继续任何传输。
func refreshDisplay(animated: Bool = true) {
guard dataSource != nil else { return }
routeButton.setTitle(viewModel.routeFilterTitle, for: .normal)
dateButton.setTitle(viewModel.dateFilterTitle, for: .normal)
routeButton.isEnabled = !viewModel.isSelectionLocked
dateButton.isEnabled = !viewModel.isSelectionLocked
routeButton.isEnabled = !viewModel.isSelectionLocked && !viewModel.isLoading
dateButton.isEnabled = !viewModel.isSelectionLocked && !viewModel.isLoading
retryButton.isHidden = viewModel.loadError == nil
emptyTitle.text = viewModel.emptyTitle
emptyMessage.text = viewModel.emptyMessage
resetButton.isHidden = viewModel.selectedRouteID == nil && viewModel.dateRange == nil
@@ -184,21 +237,26 @@ final class ScenicMaterialsViewController: BaseViewController {
private func configureFilterButton(_ button: UIButton, identifier: String) {
var configuration = UIButton.Configuration.plain()
configuration.image = UIImage(systemName: "chevron.down", withConfiguration: UIImage.SymbolConfiguration(pointSize: 10, weight: .medium))
configuration.imagePlacement = .trailing
configuration.imagePadding = 8
configuration.baseForegroundColor = ScenicMaterialsStyle.text
configuration.contentInsets = NSDirectionalEdgeInsets(top: 8, leading: 12, bottom: 8, trailing: 12)
configuration.cornerStyle = .fixed
configuration.background.cornerRadius = 11
configuration.contentInsets = NSDirectionalEdgeInsets(top: 8, leading: 12, bottom: 8, trailing: 32)
configuration.titleTextAttributesTransformer = UIConfigurationTextAttributesTransformer { incoming in
var result = incoming; result.font = .systemFont(ofSize: 13); return result
var result = incoming; result.font = .systemFont(ofSize: 15, weight: .medium); return result
}
button.configuration = configuration
button.backgroundColor = UIColor(hex: 0xF6F7F9)
button.layer.cornerRadius = 10
button.layer.borderWidth = 0.5
button.contentHorizontalAlignment = .leading
button.backgroundColor = UIColor(hex: 0xF7F8FA)
button.layer.cornerRadius = 11
button.layer.borderWidth = 1
button.layer.borderColor = ScenicMaterialsStyle.border.cgColor
button.titleLabel?.lineBreakMode = .byTruncatingTail
button.accessibilityIdentifier = identifier
let chevron = UIImageView(image: UIImage(systemName: "chevron.down", withConfiguration: UIImage.SymbolConfiguration(pointSize: 10, weight: .medium)))
chevron.tintColor = ScenicMaterialsStyle.secondary
chevron.isUserInteractionEnabled = false
button.addSubview(chevron)
chevron.snp.makeConstraints { $0.trailing.equalToSuperview().inset(12); $0.centerY.equalToSuperview() }
}
private func setupEmptyView() {
@@ -213,7 +271,10 @@ final class ScenicMaterialsViewController: BaseViewController {
resetButton.tintColor = ScenicMaterialsStyle.primary
resetButton.accessibilityIdentifier = "scenic.materials.resetFilters"
emptyView.accessibilityIdentifier = "scenic.materials.empty"
let stack = UIStackView(arrangedSubviews: [icon, emptyTitle, emptyMessage, resetButton])
retryButton.setTitle("重新加载", for: .normal)
retryButton.accessibilityIdentifier = "scenic.materials.retry"
retryButton.addTarget(self, action: #selector(reloadRemoteMaterials), for: .touchUpInside)
let stack = UIStackView(arrangedSubviews: [icon, emptyTitle, emptyMessage, resetButton, retryButton])
stack.axis = .vertical
stack.spacing = 14
emptyView.addSubview(stack)
@@ -246,7 +307,7 @@ final class ScenicMaterialsViewController: BaseViewController {
return cell
case .retention, .end:
let cell = list.dequeueReusableCell(withReuseIdentifier: "text", for: path) as! ScenicMaterialTextCell
cell.configure(item == .retention ? "素材保留 90 天,请及时下载" : "已显示保留期内的全部演示记录", identifier: item == .retention ? "scenic.materials.retention" : "scenic.materials.end")
cell.configure(item == .retention ? self.viewModel.retentionTips : (self.viewModel.isRemote ? "已显示全部素材" : "已显示保留期内的全部演示记录"), identifier: item == .retention ? "scenic.materials.retention" : "scenic.materials.end")
return cell
}
}
@@ -265,7 +326,7 @@ final class ScenicMaterialsViewController: BaseViewController {
let completed = viewModel.completedIDs.contains(clip.id)
let failed = viewModel.failedIDs.contains(clip.id)
let inBatch = viewModel.batchItemIDs.contains(clip.id)
let status: String? = completed ? "演示已下载" : failed ? "下载失败" : inBatch && viewModel.phase == .paused ? "已暂停" : nil
let status: String? = completed ? (viewModel.isRemote ? "已保存相册" : "演示已下载") : failed ? "下载失败" : inBatch && viewModel.phase == .paused ? "已暂停" : nil
cell.configure(clip: clip, selected: viewModel.selectedIDs.contains(clip.id),
isSelectionEnabled: viewModel.canSelect(id: clip.id), statusText: status,
progress: inBatch && viewModel.phase == .downloading && !completed ? viewModel.progressByID[clip.id] ?? 0 : nil,
@@ -356,20 +417,20 @@ final class ScenicMaterialsViewController: BaseViewController {
let total = viewModel.totalCount
switch viewModel.phase {
case .idle:
footer.configure(title: "已选 \(viewModel.selectedCount) 段", detail: "本地演示 · 不下载或保存真实文件",
primaryTitle: viewModel.selectedCount > 0 ? "下载所选(\(viewModel.selectedCount))" : "下载所选", primaryEnabled: viewModel.canStartDownload)
footer.configure(title: "已选 \(viewModel.selectedCount) 段", detail: viewModel.isRemote ? nil : "本地演示 · 不下载或保存真实文件",
primaryTitle: "下载所选", primaryEnabled: viewModel.canStartDownload)
case .downloading:
footer.configure(title: "下载中 · \(completed)/\(total) 段", detail: "请保持页面开启,切后台将暂停",
primaryTitle: "正在下载…", primaryEnabled: false, secondaryTitle: "取消", progress: Float(viewModel.downloadProgress))
primaryTitle: "正在下载…", primaryEnabled: false, secondaryTitle: "取消", progress: Float(viewModel.downloadProgress), layout: .progress, isBusy: true)
case .paused:
footer.configure(title: "已暂停 · 已完成 \(completed)/\(total) 段", detail: "演示进度已保留,请手动继续",
primaryTitle: "继续下载", primaryEnabled: true, secondaryTitle: "取消")
footer.configure(title: "已暂停 · 已完成 \(completed)/\(total) 段", detail: "已完成项已保留,请手动继续",
primaryTitle: "继续下载", primaryEnabled: true, secondaryTitle: "取消", progress: Float(viewModel.downloadProgress), layout: .progress)
case .partialFailure:
footer.configure(title: "演示完成 \(completed) 段 · 失败 \(viewModel.failedCount) 段", detail: "未保存真实文件,成功项不重复下载",
primaryTitle: "重试失败(\(viewModel.failedCount))", primaryEnabled: true, secondaryTitle: "继续选择")
footer.configure(title: "已下载 \(completed) 段 · 失败 \(viewModel.failedCount) 段", detail: viewModel.isRemote ? "成功项已保存相册" : "演示结果 · 未保存真实文件",
primaryTitle: "重试失败(\(viewModel.failedCount))", primaryEnabled: true, secondaryTitle: "继续选择", layout: .result)
case .completed:
footer.configure(title: "演示完成 \(completed) 段", detail: "未写入系统相册",
primaryTitle: "继续选择素材", primaryEnabled: true)
footer.configure(title: viewModel.isRemote ? "已保存 \(completed) 段" : "演示完成 \(completed) 段", detail: viewModel.isRemote ? "可在系统相册查看" : "未写入系统相册",
primaryTitle: "继续选择素材", primaryEnabled: true, layout: .result)
}
}
@@ -377,7 +438,27 @@ final class ScenicMaterialsViewController: BaseViewController {
if viewModel.phase == .completed {
viewModel.continueSelecting(); refreshDisplay(); return
}
if viewModel.isRemote {
guard authorizationTask == nil else { return }
authorizationTask = Task { @MainActor [weak self] in
let status = await PHPhotoLibrary.requestAuthorization(for: .addOnly)
guard let self else { return }
self.authorizationTask = nil
guard !Task.isCancelled, self.view.window != nil,
UIApplication.shared.applicationState == .active else { return }
guard status == .authorized || status == .limited else {
self.presentPhotoPermissionSettings()
return
}
self.startTransfer()
}
return
}
guard isDemoPhotoPermissionAllowed else { presentPermissionDemo(); return }
startTransfer()
}
private func startTransfer() {
let started: Bool
switch viewModel.phase {
case .idle: started = viewModel.startDownload()
@@ -386,11 +467,25 @@ final class ScenicMaterialsViewController: BaseViewController {
case .downloading, .completed: started = false
}
refreshDisplay(animated: false)
if started { driver.start(viewModel: viewModel) { [weak self] in self?.refreshDisplay(animated: false) } }
guard started else { return }
if viewModel.isRemote, let batchID = viewModel.batchID {
let items = viewModel.pendingIDs.compactMap { id -> ScenicMaterialDownloadItem? in
guard let clip = viewModel.clip(id: id), let url = clip.remoteURL else { return nil }
return ScenicMaterialDownloadItem(id: id, remoteURL: url,
fileName: url.pathExtension.isEmpty ? "scenic-material.mp4" : url.lastPathComponent)
}
downloadService.start(items: items, batchID: batchID) { [weak self] id, token, event in
self?.viewModel.receive(event, clipID: id, batchID: token)
self?.refreshDisplay(animated: false)
} onFailure: { [weak self] _, error in self?.showToast(error.localizedDescription) }
} else {
driver.start(viewModel: viewModel) { [weak self] in self?.refreshDisplay(animated: false) }
}
}
@objc private func pauseForBackground() {
driver.stop()
downloadService.stop()
viewModel.pauseDownload()
if isViewLoaded { refreshDisplay(animated: false) }
}
@@ -400,6 +495,7 @@ final class ScenicMaterialsViewController: BaseViewController {
let picker = ScenicMaterialRouteFilterViewController(routes: viewModel.routes, selectedRouteID: viewModel.selectedRouteID)
picker.onSelectRoute = { [weak self] id in
self?.viewModel.setRoute(id: id)
self?.reloadRemoteMaterials()
self?.refreshDisplay()
self?.collectionView.setContentOffset(.zero, animated: false)
}
@@ -414,6 +510,7 @@ final class ScenicMaterialsViewController: BaseViewController {
picker.onSelectRange = { [weak self] start, end in
guard let self else { return }
if self.viewModel.setDateRange(start: start, end: end) {
self.reloadRemoteMaterials()
self.refreshDisplay()
self.collectionView.setContentOffset(.zero, animated: false)
} else { self.showToast("请选择保留期内的有效日期范围") }
@@ -423,6 +520,7 @@ final class ScenicMaterialsViewController: BaseViewController {
@objc private func resetFilters() {
viewModel.resetFilters()
reloadRemoteMaterials()
refreshDisplay()
}
@@ -433,6 +531,16 @@ final class ScenicMaterialsViewController: BaseViewController {
present(controller, animated: true)
}
private func presentPhotoPermissionSettings() {
guard presentedViewController == nil else { return }
let alert = UIAlertController(title: "需要相册保存权限", message: "请允许添加照片和视频,以保存所选素材。", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "取消", style: .cancel))
alert.addAction(UIAlertAction(title: "去设置", style: .default) { _ in
if let url = URL(string: UIApplication.openSettingsURLString) { UIApplication.shared.open(url) }
})
present(alert, animated: true)
}
private func presentPermissionDemo() {
guard presentedViewController == nil else { return }
let alert = UIAlertController(title: "需要相册保存权限", message: "真实下载需允许保存视频。此处仅演示权限流程,不读取或修改系统权限。", preferredStyle: .alert)