feat: 完善机巢图传、拍摄阶段与任务交互

- 完善双路 RTC 接收、首帧切换及拍摄结束后的本地播放释放
- 对齐无人机状态枚举与正常拍完返航标记,新增到达后本地倒计时
- 补充准备页电量与前往回执,进入任务时移除准备页路由
- 对齐拍摄中和拍摄完成原型布局,移除详情按钮
- 补充隔离测试、接口记录与项目约定

验证:最近 157 项相关模拟器隔离测试通过,Release 无签名编译通过;未调用真实飞控或图传。
This commit is contained in:
2026-11-03 16:43:23 +08:00
parent 0ed0077ec4
commit 54210925f0
33 changed files with 3242 additions and 205 deletions
@@ -0,0 +1,86 @@
import SnapKit
import UIKit
/// 与任务原型一致的录制完成提示;只引导查看素材,不宣告上传成功或扣减次数。
@MainActor
final class DroneDockRecordingCompletionView: UIView {
/// 关闭提示并继续留在任务页。
var onLater: (() -> Void)?
/// 前往当前订单素材库。
var onViewMaterials: (() -> Void)?
/// 创建居中结果卡片,覆盖任务页但不触发生命周期或暂停只读状态更新。
override init(frame: CGRect) {
super.init(frame: frame)
setupUI()
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
private func setupUI() {
backgroundColor = .black.withAlphaComponent(0.5)
accessibilityViewIsModal = true
accessibilityIdentifier = "drone.task.recordingCompletion"
let card = UIView()
card.backgroundColor = .white
card.layer.cornerRadius = 14
addSubview(card)
let symbol = UIImageView(image: UIImage(systemName: "checkmark.circle.fill"))
symbol.tintColor = DroneDockStyle.success
symbol.contentMode = .scaleAspectFit
let title = DroneDockStyle.label(size: 20, weight: .semibold)
title.text = "拍摄已完成"
title.textAlignment = .center
let message = DroneDockStyle.label(size: 14, color: DroneDockStyle.secondary)
message.text = "本次拍摄已完成,\n可前往订单素材库查看上传进度和素材。"
message.numberOfLines = 0
message.textAlignment = .center
let later = button("稍后再去", primary: false, action: #selector(laterTapped))
let materials = button("去查看", primary: true, action: #selector(materialsTapped))
later.accessibilityIdentifier = "drone.task.recordingCompletion.later"
materials.accessibilityIdentifier = "drone.task.recordingCompletion.materials"
let actions = UIStackView(arrangedSubviews: [later, materials])
actions.spacing = 10
actions.distribution = .fillEqually
[symbol, title, message, actions].forEach { card.addSubview($0) }
card.snp.makeConstraints { make in
make.center.equalToSuperview()
make.width.equalTo(320).priority(.high)
make.leading.greaterThanOrEqualToSuperview().offset(24)
make.trailing.lessThanOrEqualToSuperview().offset(-24)
}
symbol.snp.makeConstraints { make in
make.top.equalToSuperview().offset(24)
make.centerX.equalToSuperview()
make.size.equalTo(50)
}
title.snp.makeConstraints { make in
make.top.equalTo(symbol.snp.bottom).offset(16)
make.leading.trailing.equalToSuperview().inset(20)
}
message.snp.makeConstraints { make in
make.top.equalTo(title.snp.bottom).offset(12)
make.leading.trailing.equalToSuperview().inset(20)
}
actions.snp.makeConstraints { make in
make.top.equalTo(message.snp.bottom).offset(24)
make.leading.trailing.bottom.equalToSuperview().inset(16)
make.height.equalTo(46)
}
}
private func button(_ title: String, primary: Bool, action: Selector) -> UIButton {
let button = UIButton(type: .system)
button.setTitle(title, for: .normal)
button.setTitleColor(primary ? .white : DroneDockStyle.text, for: .normal)
button.titleLabel?.font = .systemFont(ofSize: 15, weight: .semibold)
button.backgroundColor = primary ? DroneDockStyle.primary : UIColor(hex: 0xEEF0F6)
button.layer.cornerRadius = 7
button.addTarget(self, action: action, for: .touchUpInside)
return button
}
@objc private func laterTapped() { onLater?() }
@objc private func materialsTapped() { onViewMaterials?() }
}
@@ -36,7 +36,9 @@ final class DroneDockRemotePreparationViewController: BaseViewController {
self.viewModel = viewModel
self.simulationRecordsProvider = simulationRecordsProvider
self.taskControllerFactory = taskControllerFactory ?? { taskID, order, context in
DroneDockShootingTaskEntry.makeController(taskID: taskID, order: order, context: context)
DroneDockShootingTaskEntry.makeController(taskID: taskID, order: order, context: context,
coverURL: viewModel.selectedSpot?.displayCoverURL,
initialSummonReceipt: viewModel.shootResponse)
}
self.planeStatusPollDelay = planeStatusPollDelay
super.init(nibName: nil, bundle: nil)
@@ -222,7 +224,7 @@ final class DroneDockRemotePreparationViewController: BaseViewController {
present(alert, animated: true)
}
/// 成功后自动导航一次;失败的已结束任务只在用户明确点击时查看原任务。
/// 进入任务时替换有前驱的准备页,返回直达工作台;独立调试根页保留原返回入口。
@discardableResult
private func openShootingTask(automatically: Bool) -> Bool {
guard isPageVisible, isApplicationActive, viewModel.canOpenShootingTask,
@@ -232,7 +234,12 @@ final class DroneDockRemotePreparationViewController: BaseViewController {
DroneDockDiagnostics.event("navigation.open_task", taskID: taskID)
automaticallyOpenedTaskID = taskID
let controller = taskControllerFactory(taskID, viewModel.order, viewModel.context)
navigationController.pushViewController(controller, animated: true)
let stack = navigationController.viewControllers
if stack.count > 1 {
navigationController.setViewControllers(Array(stack.dropLast()) + [controller], animated: true)
} else {
navigationController.pushViewController(controller, animated: true)
}
return true
}
@@ -6,6 +6,13 @@ enum DroneDockShootingTaskEntry {
/// 使用已有任务读取状态;Release 注入已授权的真实控制,Debug 保持只读。
static func makeController(taskID: Int, order: DroneDockHomeOrder,
context: DroneDockHomeContext) -> UIViewController {
makeController(taskID: taskID, order: order, context: context, coverURL: nil)
}
/// 准备页携带封面及召唤回执;其它入口不推断前往阶段,等 shooting 返回。
static func makeController(taskID: Int, order: DroneDockHomeOrder,
context: DroneDockHomeContext, coverURL: URL?,
initialSummonReceipt: DroneDockShootResponse? = nil) -> UIViewController {
let client = NetworkServices.shared.apiClient
let realtime = DroneDockShootingRealtimeSession(taskID: taskID,
ticketService: DroneDockSocketTokenAPI(client: client),
@@ -22,7 +29,8 @@ enum DroneDockShootingTaskEntry {
startService: DeviceCommandDebugPolicy.blocksFlightRequests ? nil : DroneDockStartShootAPI(client: client),
commandService: DeviceCommandDebugPolicy.blocksFlightRequests ? nil : DroneDockCommandAPI(client: client),
resummonService: DeviceCommandDebugPolicy.blocksFlightRequests ? nil : DroneDockShootAPI(client: client),
initialSummonReceipt: initialSummonReceipt,
currentContext: { DroneDockHomeViewController.currentContext() }
), liveViewModel: live, realtimeSession: realtime)
), liveViewModel: live, coverURL: coverURL, realtimeSession: realtime)
}
}
@@ -43,17 +43,27 @@ final class DroneDockShootingTaskViewController: BaseViewController {
private var isSendingSafetyAction = false
private var isResummoningAction = false
private var wasRealtimeLive = false
private let coverURL: URL?
private var finishedExecutions: Set<String> = []
private var displayedCompletionIDs: Set<String> = []
private var completionNotice: DroneDockRecordingCompletionView?
private let countdownDelay: @Sendable () async throws -> Void
private var countdownTask: Task<Void, Never>?
private var countdownGeneration = 0
/// 构造时只保存依赖,首次 GET 必须等页面完整出现后才发送。
init(viewModel: DroneDockShootingTaskViewModel,
liveViewModel: DroneDockLiveViewModel? = nil,
livePlayer: (any DroneDockLivePlaying)? = nil,
coverURL: URL? = nil,
realtimeSession: DroneDockShootingRealtimeSession? = nil,
materialsControllerFactory: (@MainActor (DroneDockHomeOrder, DroneDockHomeContext) -> UIViewController)? = nil,
simulationRecordsProvider: (@MainActor () -> String)? = nil,
shootingPollDelay: @escaping @Sendable (UInt64) async throws -> Void = { try await Task.sleep(nanoseconds: $0) },
liveParameterDelay: @escaping @Sendable (TimeInterval) async throws -> Void = { try await Task.sleep(for: .seconds($0)) }) {
liveParameterDelay: @escaping @Sendable (TimeInterval) async throws -> Void = { try await Task.sleep(for: .seconds($0)) },
countdownDelay: @escaping @Sendable () async throws -> Void = { try await Task.sleep(for: .seconds(1)) }) {
self.viewModel = viewModel
self.coverURL = coverURL
self.feedPlaceholder = livePlayer.map { DroneDockTaskLiveView(rtcPlayer: $0) } ?? DroneDockTaskLiveView()
self.realtimeSession = realtimeSession
self.liveViewModel = liveViewModel ?? DroneDockLiveViewModel(
@@ -62,6 +72,7 @@ final class DroneDockShootingTaskViewController: BaseViewController {
self.simulationRecordsProvider = simulationRecordsProvider
self.shootingPollDelay = shootingPollDelay
self.liveParameterDelay = liveParameterDelay
self.countdownDelay = countdownDelay
self.materialsControllerFactory = materialsControllerFactory ?? { order, context in
DroneDockMaterialsViewController(viewModel: DroneDockMaterialsViewModel(
context: context, order: order,
@@ -92,6 +103,7 @@ final class DroneDockShootingTaskViewController: BaseViewController {
resummonTask?.cancel()
liveTask?.cancel()
liveParameterTask?.cancel()
countdownTask?.cancel()
NotificationCenter.default.removeObserver(self)
}
@@ -228,6 +240,7 @@ final class DroneDockShootingTaskViewController: BaseViewController {
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
isPageVisible = false
dismissCompletionNotice()
logEvent("page.disappeared")
cancelRefresh()
stopLive()
@@ -235,26 +248,103 @@ final class DroneDockShootingTaskViewController: BaseViewController {
private func applySnapshot() {
guard isViewLoaded else { return }
if viewModel.isRecordingFinished { finishedExecutions.insert(viewModel.recordingExecutionID) }
let recordingFinished = finishedExecutions.contains(viewModel.recordingExecutionID)
if !viewModel.shouldPresentRecordingCompletion { dismissCompletionNotice() }
if recordingFinished, liveTask != nil || liveParameterTask != nil || liveViewModel.playbackSessionID != nil || liveViewModel.playbackURL != nil {
stopLive()
}
feedPlaceholder.showRecordingCover(recordingFinished, url: coverURL)
let loading = (viewModel.response == nil && (isRequesting || viewModel.isLoading))
|| isStartingAction || viewModel.isStartingShooting
|| isSendingSafetyAction || viewModel.isSendingCommand || isResummoningAction || viewModel.isResummoning
feedPlaceholder.apply(liveViewModel)
feedPlaceholder.setPlaybackActive(isPageVisible && isApplicationActive)
feedPlaceholder.setPlaybackActive(isPageVisible && isApplicationActive && !recordingFinished)
taskTitleLabel.text = viewModel.title
subtitleLabel.text = viewModel.subtitle + (viewModel.response?.metricsStale == true ? " · 读数已过期" : "")
let telemetry = viewModel.telemetry
telemetryView.apply(values: [telemetry.batteryText, telemetry.temperatureText, telemetry.windText,
telemetry.rainText, telemetry.signalText, telemetry.satelliteText],
isStale: viewModel.isTelemetryStale, accessibilityPrefix: "drone.task.remote.metric", preservingStaleValues: true)
let value = loading && viewModel.response == nil ? DroneDockTaskPresentation(
let presentation = viewModel.presentation
let value = loading && viewModel.response == nil && presentation.phase != .navigating ? DroneDockTaskPresentation(
phase: .loading, title: "正在获取任务状态", message: "正在读取当前拍摄任务",
deviceStatus: "—", action: .none, actionTitle: nil, isActionEnabled: false) : viewModel.presentation
deviceStatus: "—", action: .none, actionTitle: nil, isActionEnabled: false) : presentation
statusView.apply(value, isRefreshing: loading)
updateArrivalCountdown()
safetyView.apply(model: viewModel, isSimulation: simulationRecordsProvider != nil,
isInteractive: isPageVisible && isApplicationActive && !loading)
statusView.isUserInteractionEnabled = isPageVisible && isApplicationActive && !loading
navigationItem.rightBarButtonItems?.forEach { $0.isEnabled = isPageVisible && isApplicationActive && !loading }
navigationItem.rightBarButtonItem?.accessibilityValue = loading ? "正在刷新" : nil
presentCompletionNoticeIfNeeded()
refreshLiveIfVisible(automatically: true)
}
/// 倒计时只更新独立秒数标签;网络读取、飞控及后端阶段仍由原有流程驱动。
private func updateArrivalCountdown() {
let seconds = viewModel.countdownRemainingSeconds
statusView.updateCountdown(seconds: seconds)
guard isPageVisible, isApplicationActive, let seconds, seconds > 0 else {
stopArrivalCountdown()
return
}
guard countdownTask == nil else { return }
countdownGeneration += 1
let generation = countdownGeneration
let delay = countdownDelay
countdownTask = Task { @MainActor [weak self] in
while !Task.isCancelled {
do { try await delay() } catch { return }
guard let self, !Task.isCancelled, self.countdownGeneration == generation,
self.isPageVisible, self.isApplicationActive else { return }
let remaining = self.viewModel.countdownRemainingSeconds
self.statusView.updateCountdown(seconds: remaining)
if remaining == nil || remaining == 0 {
self.countdownTask = nil
return
}
}
}
}
private func stopArrivalCountdown() {
countdownGeneration += 1
countdownTask?.cancel()
countdownTask = nil
}
private func presentCompletionNoticeIfNeeded() {
let id = viewModel.recordingExecutionID
guard viewModel.shouldPresentRecordingCompletion, isPageVisible, isApplicationActive, view.window != nil,
presentedViewController == nil, completionNotice == nil, !displayedCompletionIDs.contains(id) else { return }
displayedCompletionIDs.insert(id)
let notice = DroneDockRecordingCompletionView()
completionNotice = notice
notice.onLater = { [weak self] in self?.dismissCompletionNotice() }
notice.onViewMaterials = { [weak self] in
guard let self, self.isPageVisible, self.isApplicationActive,
self.viewModel.recordingExecutionID == id else { return }
self.dismissCompletionNotice()
self.openMaterials()
}
let container = navigationController?.view ?? view!
container.addSubview(notice)
notice.snp.makeConstraints { $0.edges.equalToSuperview() }
UIAccessibility.post(notification: .screenChanged, argument: notice)
}
private func dismissCompletionNotice() {
completionNotice?.removeFromSuperview()
completionNotice = nil
}
private func openMaterials() {
guard isPageVisible, isApplicationActive, presentedViewController == nil,
viewModel.presentation.action == .materials, viewModel.presentation.isActionEnabled,
let navigationController, navigationController.topViewController === self else { return }
dismissCompletionNotice()
navigationController.pushViewController(materialsControllerFactory(viewModel.order, viewModel.context), animated: true)
}
private func primaryActionTriggered() {
@@ -274,8 +364,7 @@ final class DroneDockShootingTaskViewController: BaseViewController {
case .retry:
resummonIfAllowed()
case .materials:
guard let navigationController, navigationController.topViewController === self else { return }
navigationController.pushViewController(materialsControllerFactory(viewModel.order, viewModel.context), animated: true)
openMaterials()
case .resume, .none:
break
}
@@ -366,6 +455,7 @@ final class DroneDockShootingTaskViewController: BaseViewController {
}
private func cancelRefresh() {
stopArrivalCountdown()
wasRealtimeLive = false
realtimeSession?.stop()
cancelScheduledPoll()
@@ -473,6 +563,8 @@ final class DroneDockShootingTaskViewController: BaseViewController {
/// 可见且活跃时自动开启一次;失败可手动重试,不随 shooting/Socket 刷新重复请求。
private func refreshLiveIfVisible(automatically: Bool = false, keepingPlayback: Bool = false) {
guard viewModel.response != nil, viewModel.readAccessError == nil,
!finishedExecutions.contains(viewModel.recordingExecutionID), !viewModel.isRecordingFinished else { return }
guard !automatically || liveViewModel.loadsAutomatically else { return }
guard isPageVisible, isApplicationActive, liveTask == nil, liveViewModel.canLoad else { return }
liveParameterTask?.cancel()
@@ -0,0 +1,133 @@
import SnapKit
import UIKit
/// 拍摄完成区域:左侧完成图标、右侧状态说明以及整行素材入口。
@MainActor
final class DroneDockTaskCompletedView: UIView {
/// 用户点击已允许的素材入口时通知任务页面。
var onViewMaterials: (() -> Void)?
/// 与任务固定区域共享紧凑布局指标,操作区域始终至少 44 点高。
private(set) var usesCompactLayout = false
private let content = UIView()
private let iconBackground = UIView()
private let icon = UIImageView(image: UIImage(systemName: "checkmark.circle.fill"))
private let titleLabel = DroneDockStyle.label(size: 20, weight: .semibold)
private let messageLabel = DroneDockStyle.label(size: 14, color: DroneDockStyle.secondary)
private let materialsButton = UIButton(type: .system)
private var messageHeight: Constraint?
private var titleHeight: Constraint?
private var buttonHeight: Constraint?
/// 创建不包含设备摘要或次级详情按钮的完成面板。
override init(frame: CGRect) {
super.init(frame: frame)
setupUI()
setupConstraints()
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
/// 仅展示已确认的完成文案,素材入口继续服从任务门禁与页面刷新状态。
func apply(_ presentation: DroneDockTaskPresentation, isRefreshing: Bool) {
titleLabel.text = presentation.title
messageLabel.text = presentation.message
var configuration = materialsButton.configuration
configuration?.title = presentation.actionTitle
materialsButton.isEnabled = presentation.action == .materials && presentation.isActionEnabled && !isRefreshing
configuration?.baseBackgroundColor = DroneDockStyle.primary.withAlphaComponent(materialsButton.isEnabled ? 1 : 0.35)
materialsButton.configuration = configuration
setNeedsLayout()
}
/// 仅当前可见面板提供通用任务访问标识,防止状态切换后匹配到隐藏控件。
func setIdentifiersActive(_ active: Bool) {
titleLabel.accessibilityIdentifier = active ? "drone.task.remote.statusTitle" : nil
messageLabel.accessibilityIdentifier = active ? "drone.task.remote.statusMessage" : nil
materialsButton.accessibilityIdentifier = active ? "drone.task.remote.primary" : nil
}
/// 固定区域变小时收紧说明行数与间距,不改变整页布局或缩小点击区域。
override func layoutSubviews() {
usesCompactLayout = bounds.height < 190
let extreme = bounds.height < 120
titleLabel.font = .systemFont(ofSize: extreme ? 17 : 20, weight: .semibold)
messageLabel.font = .systemFont(ofSize: usesCompactLayout ? 13 : 14)
messageLabel.numberOfLines = usesCompactLayout ? 2 : 3
let width = max(1, bounds.width - 84)
let measured = messageLabel.sizeThatFits(CGSize(width: width, height: .greatestFiniteMagnitude)).height
let title = ceil(titleLabel.font.lineHeight)
let button: CGFloat = usesCompactLayout ? 44 : 50
let availableMessageHeight = max(0, bounds.height - 24 - title - 6 - 16 - button)
let body = min(ceil(measured), availableMessageHeight)
messageLabel.isHidden = body < messageLabel.font.lineHeight
messageHeight?.update(offset: messageLabel.isHidden ? 0 : body)
titleHeight?.update(offset: title)
buttonHeight?.update(offset: button)
super.layoutSubviews()
}
private func setupUI() {
accessibilityIdentifier = "drone.task.remote.completed"
addSubview(content)
[iconBackground, titleLabel, messageLabel, materialsButton].forEach(content.addSubview)
iconBackground.addSubview(icon)
iconBackground.backgroundColor = DroneDockStyle.success.withAlphaComponent(0.12)
iconBackground.layer.cornerRadius = 20
icon.contentMode = .scaleAspectFit
icon.tintColor = DroneDockStyle.success
titleLabel.accessibilityTraits = .header
titleLabel.numberOfLines = 1
titleLabel.lineBreakMode = .byTruncatingTail
messageLabel.lineBreakMode = .byTruncatingTail
var configuration = UIButton.Configuration.filled()
configuration.baseForegroundColor = .white
configuration.background.cornerRadius = 8
configuration.cornerStyle = .fixed
configuration.image = UIImage(systemName: "photo", withConfiguration: UIImage.SymbolConfiguration(pointSize: 15))
configuration.imagePadding = 8
configuration.titleTextAttributesTransformer = UIConfigurationTextAttributesTransformer { attributes in
var result = attributes
result.font = .systemFont(ofSize: 15, weight: .semibold)
return result
}
materialsButton.configuration = configuration
materialsButton.addTarget(self, action: #selector(viewMaterials), for: .touchUpInside)
}
private func setupConstraints() {
content.snp.makeConstraints { make in
make.leading.trailing.equalToSuperview().inset(16)
make.centerY.equalToSuperview()
}
iconBackground.snp.makeConstraints { make in
make.top.leading.equalToSuperview()
make.size.equalTo(40)
}
icon.snp.makeConstraints { make in
make.center.equalToSuperview()
make.size.equalTo(22)
}
titleLabel.snp.makeConstraints { make in
make.top.trailing.equalToSuperview()
make.leading.equalTo(iconBackground.snp.trailing).offset(12)
titleHeight = make.height.equalTo(24).constraint
}
messageLabel.snp.makeConstraints { make in
make.top.equalTo(titleLabel.snp.bottom).offset(6)
make.leading.trailing.equalTo(titleLabel)
messageHeight = make.height.equalTo(34).constraint
}
materialsButton.snp.makeConstraints { make in
make.top.equalTo(messageLabel.snp.bottom).offset(16)
make.leading.trailing.bottom.equalToSuperview()
buttonHeight = make.height.equalTo(50).constraint
}
}
@objc private func viewMaterials() {
guard !isHidden, materialsButton.isEnabled else { return }
onViewMaterials?()
}
}
@@ -1,4 +1,5 @@
import AVFoundation
import Kingfisher
import SnapKit
import UIKit
@@ -14,6 +15,8 @@ final class DroneDockTaskLiveView: UIView {
private let titleLabel = DroneDockStyle.label(size: 15, weight: .medium, color: .white)
private let messageLabel = DroneDockStyle.label(size: 12, color: .lightGray)
private let sourceLabel = DroneDockStyle.label(size: 11, weight: .medium, color: .white)
private let sourceBadge = UIStackView()
private let liveDot = UIView()
private let requestButton = UIButton(type: .system)
private let labels = UIStackView()
private var player: AVQueuePlayer?
@@ -22,6 +25,12 @@ final class DroneDockTaskLiveView: UIView {
private var activeURL: URL?
private var isPlaybackActive = false
private let rtcView = UIView()
private let coverView = UIImageView()
private let coverShade = UIView()
private let coverIcon = UIImageView(image: UIImage(systemName: "photo.on.rectangle.angled"))
private var labelsCenterY: Constraint?
private var isShowingCover = false
private var coverURL: URL?
private let rtcPlayer: any DroneDockLivePlaying
private var requestedRTC: [DroneDockVolcLiveConfiguration] = []
private var activeRTC: [DroneDockVolcLiveConfiguration] = []
@@ -64,6 +73,7 @@ final class DroneDockTaskLiveView: UIView {
/// 在明确时机应用模型;远程 URL 即使错误传入也不会创建播放器。
func apply(_ model: DroneDockLiveViewModel) {
guard !isShowingCover else { return }
titleLabel.text = model.title
messageLabel.text = model.message
requestButton.setTitle(model.actionTitle, for: .normal)
@@ -74,8 +84,9 @@ final class DroneDockTaskLiveView: UIView {
requestedSessionID = model.playbackSessionID
let hasLocalPreview = requestedURL != nil
let isPlaying = model.state == .playing
sourceLabel.text = hasLocalPreview ? "本地模拟画面 · 未连接无人机" : (isPlaying ? model.message + " · 实时图传" : nil)
sourceLabel.isHidden = !hasLocalPreview && !isPlaying
sourceLabel.text = hasLocalPreview ? "本地模拟画面 · 未连接无人机" : "实时图传"
sourceBadge.isHidden = !hasLocalPreview && !isPlaying
liveDot.isHidden = hasLocalPreview
titleLabel.isHidden = hasLocalPreview || isPlaying
messageLabel.isHidden = hasLocalPreview || isPlaying
accessibilityLabel = hasLocalPreview || isPlaying ? sourceLabel.text : "\(model.title),\(model.message)"
@@ -84,10 +95,32 @@ final class DroneDockTaskLiveView: UIView {
/// 页面离开或进入后台立即释放播放器;重新获取图传参数由控制器协调。
func setPlaybackActive(_ active: Bool) {
isPlaybackActive = active
isPlaybackActive = active && !isShowingCover
updatePlayback()
}
/// 录制结束后仅展示静态封面;隐藏实时标记和重试按钮,旧模型不能恢复播放。
func showRecordingCover(_ show: Bool, url: URL?) {
guard isShowingCover != show || coverURL != url else { return }
isShowingCover = show
coverURL = url
coverView.isHidden = !show
coverShade.isHidden = !show
coverIcon.isHidden = !show || url != nil
labelsCenterY?.update(offset: show ? 38 : -15)
guard show else { coverView.kf.cancelDownloadTask(); return }
setPlaybackActive(false)
coverView.contentMode = .scaleAspectFill
coverView.kf.setImage(with: url)
titleLabel.text = "拍摄已完成"
titleLabel.isHidden = false
messageLabel.text = "拍摄封面 · 实时图传已结束"
messageLabel.isHidden = false
sourceBadge.isHidden = true
requestButton.isHidden = true
accessibilityLabel = "拍摄已完成,拍摄封面,实时图传已结束"
}
private func setupUI() {
backgroundColor = UIColor(hex: 0x171B22)
clipsToBounds = true
@@ -95,6 +128,19 @@ final class DroneDockTaskLiveView: UIView {
layer.addSublayer(playerLayer)
rtcView.backgroundColor = .clear
addSubview(rtcView)
coverView.backgroundColor = UIColor(hex: 0x182A36)
coverView.tintColor = UIColor.white.withAlphaComponent(0.22)
coverView.clipsToBounds = true
coverView.isHidden = true
coverView.accessibilityIdentifier = "drone.task.remote.live.cover"
addSubview(coverView)
coverShade.backgroundColor = .black.withAlphaComponent(0.3)
coverShade.isHidden = true
addSubview(coverShade)
coverIcon.contentMode = .scaleAspectFit
coverIcon.tintColor = .white.withAlphaComponent(0.7)
coverIcon.isHidden = true
addSubview(coverIcon)
playerLayer.videoGravity = .resizeAspect
titleLabel.textAlignment = .center
messageLabel.textAlignment = .center
@@ -102,11 +148,16 @@ final class DroneDockTaskLiveView: UIView {
messageLabel.accessibilityIdentifier = "drone.task.remote.live.status"
titleLabel.accessibilityIdentifier = "drone.task.remote.live.title"
sourceLabel.accessibilityIdentifier = "drone.task.remote.live.source"
sourceLabel.backgroundColor = UIColor.black.withAlphaComponent(0.65)
sourceLabel.textAlignment = .center
sourceLabel.layer.cornerRadius = 4
sourceLabel.clipsToBounds = true
sourceLabel.isHidden = true
sourceBadge.axis = .horizontal
sourceBadge.alignment = .center
sourceBadge.spacing = 6
sourceBadge.isHidden = true
sourceBadge.accessibilityIdentifier = "drone.task.remote.live.badge"
liveDot.backgroundColor = DroneDockStyle.success
liveDot.layer.cornerRadius = 3
liveDot.accessibilityIdentifier = "drone.task.remote.live.dot"
sourceBadge.addArrangedSubview(liveDot)
sourceBadge.addArrangedSubview(sourceLabel)
requestButton.tintColor = .white
requestButton.titleLabel?.font = .systemFont(ofSize: 13, weight: .medium)
requestButton.backgroundColor = UIColor.black.withAlphaComponent(0.45)
@@ -119,14 +170,21 @@ final class DroneDockTaskLiveView: UIView {
labels.addArrangedSubview(titleLabel)
labels.addArrangedSubview(messageLabel)
addSubview(labels)
addSubview(sourceLabel)
addSubview(sourceBadge)
addSubview(requestButton)
}
private func setupConstraints() {
rtcView.snp.makeConstraints { $0.edges.equalToSuperview() }
coverView.snp.makeConstraints { $0.edges.equalToSuperview() }
coverShade.snp.makeConstraints { $0.edges.equalToSuperview() }
coverIcon.snp.makeConstraints { make in
make.centerX.equalToSuperview()
make.centerY.equalToSuperview().offset(-28)
make.size.equalTo(42)
}
labels.snp.makeConstraints { make in
make.centerY.equalToSuperview().offset(-15)
labelsCenterY = make.centerY.equalToSuperview().offset(-15).constraint
make.leading.trailing.equalToSuperview().inset(20)
}
requestButton.snp.makeConstraints { make in
@@ -135,10 +193,10 @@ final class DroneDockTaskLiveView: UIView {
make.width.greaterThanOrEqualTo(150)
make.height.equalTo(36)
}
sourceLabel.snp.makeConstraints { make in
make.top.leading.equalToSuperview().inset(10)
make.height.equalTo(24)
make.width.equalTo(200)
liveDot.snp.makeConstraints { $0.size.equalTo(6).priority(999) }
sourceBadge.snp.makeConstraints { make in
make.top.leading.equalToSuperview().inset(12)
make.trailing.lessThanOrEqualToSuperview().inset(12)
}
}
@@ -0,0 +1,191 @@
import SnapKit
import UIKit
/// 拍摄中状态区域:对齐体验网页的蓝色视频提示和禁用状态按钮,不执行任何操作。
@MainActor
final class DroneDockTaskShootingView: UIView {
/// 当前内容采用的排版参考比例,不通过 transform 缩小整个视图。
private(set) var effectiveScale: CGFloat = 1
/// 固定区域较小时收紧图标、字号和间距。
private(set) var usesCompactLayout = false
private let content = UIView()
private let header = UIView()
private let iconBackground = UIView()
private let icon = UIImageView(image: UIImage(systemName: "video.fill"))
private let titleLabel = DroneDockStyle.label(size: 23, weight: .semibold, color: UIColor(hex: 0x101523))
private let messageLabel = DroneDockStyle.label(size: 14, color: UIColor(hex: 0x6A79A0))
private let indicatorButton = UIButton(type: .system)
private var presentation: DroneDockTaskPresentation?
private var headerHeight: Constraint?
private var iconSize: Constraint?
private var textLeading: Constraint?
private var titleHeight: Constraint?
private var messageTop: Constraint?
private var messageHeight: Constraint?
private var indicatorTop: Constraint?
private var indicatorHeight: Constraint?
/// 建立纯展示的拍摄中面板,外部任务页决定固定区域大小。
override init(frame: CGRect) {
super.init(frame: frame)
setupUI()
setupConstraints()
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
/// 展示已确认的拍摄中文案,按钮始终仅作状态指示。
func apply(_ presentation: DroneDockTaskPresentation) {
self.presentation = presentation
titleLabel.text = presentation.title
messageLabel.text = presentation.message
indicatorButton.isEnabled = false
setNeedsLayout()
}
/// 仅可见状态面板提供通用访问标识,避免匹配到隐藏的标题或说明。
func setIdentifiersActive(_ active: Bool) {
titleLabel.accessibilityIdentifier = active ? "drone.task.remote.statusTitle" : nil
messageLabel.accessibilityIdentifier = active ? "drone.task.remote.statusMessage" : nil
}
/// 按可用高度调整内部排版,状态按钮始终保留至少 44 点高度。
override func layoutSubviews() {
updateContentLayout()
super.layoutSubviews()
}
private func setupUI() {
accessibilityIdentifier = "drone.task.remote.shooting"
backgroundColor = .white
addSubview(content)
content.addSubview(header)
content.addSubview(indicatorButton)
[iconBackground, titleLabel, messageLabel].forEach(header.addSubview)
iconBackground.addSubview(icon)
iconBackground.backgroundColor = UIColor(hex: 0xE2EDFF)
iconBackground.layer.cornerRadius = 20.5
icon.contentMode = .scaleAspectFit
icon.tintColor = UIColor(hex: 0x0671FF)
titleLabel.accessibilityTraits = .header
titleLabel.numberOfLines = 1
titleLabel.lineBreakMode = .byTruncatingTail
messageLabel.numberOfLines = 2
messageLabel.lineBreakMode = .byTruncatingTail
var configuration = UIButton.Configuration.filled()
configuration.title = "拍摄中"
configuration.image = UIImage(systemName: "camera")
configuration.imagePadding = 12
configuration.preferredSymbolConfigurationForImage = UIImage.SymbolConfiguration(pointSize: 24, weight: .regular)
configuration.background.backgroundColor = UIColor(hex: 0xD7E7FF)
configuration.background.cornerRadius = 8
configuration.cornerStyle = .fixed
configuration.baseForegroundColor = UIColor(hex: 0x4D91FF)
configuration.contentInsets = NSDirectionalEdgeInsets(top: 0, leading: 8, bottom: 0, trailing: 8)
indicatorButton.configuration = configuration
indicatorButton.isEnabled = false
indicatorButton.accessibilityIdentifier = "drone.task.remote.shootingIndicator"
indicatorButton.configurationUpdateHandler = { button in
button.configuration?.background.backgroundColor = UIColor(hex: 0xD7E7FF)
button.configuration?.baseForegroundColor = UIColor(hex: 0x4D91FF)
button.configuration?.imageColorTransformer = UIConfigurationColorTransformer { _ in UIColor(hex: 0x4D91FF) }
}
}
private func setupConstraints() {
content.snp.makeConstraints { make in
make.leading.trailing.equalToSuperview().inset(18)
make.centerY.equalToSuperview()
}
header.snp.makeConstraints { make in
make.top.leading.trailing.equalToSuperview()
headerHeight = make.height.equalTo(81).constraint
}
iconBackground.snp.makeConstraints { make in
make.top.leading.equalToSuperview()
iconSize = make.size.equalTo(41).constraint
}
icon.snp.makeConstraints { make in
make.center.equalToSuperview()
make.size.equalTo(iconBackground.snp.width).multipliedBy(24.0 / 41.0)
}
titleLabel.snp.makeConstraints { make in
make.top.trailing.equalToSuperview()
textLeading = make.leading.equalTo(iconBackground.snp.trailing).offset(12).constraint
titleHeight = make.height.equalTo(30).constraint
}
messageLabel.snp.makeConstraints { make in
messageTop = make.top.equalTo(titleLabel.snp.bottom).offset(6).constraint
make.leading.trailing.equalTo(titleLabel)
messageHeight = make.height.equalTo(45).constraint
}
indicatorButton.snp.makeConstraints { make in
indicatorTop = make.top.equalTo(header.snp.bottom).offset(16).constraint
make.leading.trailing.bottom.equalToSuperview()
indicatorHeight = make.height.equalTo(50).constraint
}
}
private func updateContentLayout() {
guard let presentation, bounds.width > 0, bounds.height > 0 else { return }
usesCompactLayout = bounds.height < 190
let extreme = bounds.height < 120
let compact = usesCompactLayout
let diameter: CGFloat = extreme ? 24 : compact ? 32 : 41
let iconGap: CGFloat = extreme ? 8 : compact ? 10 : 12
let titleSize: CGFloat = extreme ? 17 : compact ? 20 : 23
let messageSize: CGFloat = compact ? 13 : 14
let title = max(ceil(UIFont.systemFont(ofSize: titleSize, weight: .semibold).lineHeight), compact ? 0 : 30)
let textGap: CGFloat = extreme ? 3 : compact ? 4 : 6
let actionGap: CGFloat = extreme ? 8 : compact ? 12 : 16
let actionHeight: CGFloat = compact ? 44 : 50
let inset: CGFloat = extreme ? 4 : 6
let textWidth = max(1, bounds.width - 36 - diameter - iconGap)
let available = max(1, bounds.height - inset * 2)
let paragraph = NSMutableParagraphStyle()
paragraph.minimumLineHeight = messageSize * 1.6
paragraph.maximumLineHeight = messageSize * 1.6
paragraph.lineBreakMode = .byTruncatingTail
titleLabel.font = .systemFont(ofSize: titleSize, weight: .semibold)
let messageFont = UIFont.systemFont(ofSize: messageSize)
messageLabel.font = messageFont
let attributes: [NSAttributedString.Key: Any] = [
.font: messageFont,
.foregroundColor: UIColor(hex: 0x6A79A0),
.paragraphStyle: paragraph
]
messageLabel.attributedText = NSAttributedString(string: presentation.message, attributes: attributes)
let measured = (presentation.message as NSString).boundingRect(
with: CGSize(width: textWidth, height: .greatestFiniteMagnitude),
options: [.usesLineFragmentOrigin, .usesFontLeading], attributes: attributes, context: nil).height
var lines = extreme || presentation.message.isEmpty ? 0 : 2
var body = lines == 0 ? 0 : ceil(min(measured, paragraph.maximumLineHeight * CGFloat(lines)))
while max(diameter, title + (lines > 0 ? textGap + body : 0)) + actionGap + actionHeight > available, lines > 0 {
lines -= 1
body = lines == 0 ? 0 : ceil(min(measured, paragraph.maximumLineHeight * CGFloat(lines)))
}
messageLabel.numberOfLines = max(1, lines)
messageLabel.isHidden = lines == 0
let header = max(diameter, title + (lines > 0 ? textGap + body : 0))
let natural = title + textGap + ceil(messageSize * 3.2) + actionGap + actionHeight
effectiveScale = min(1, max(0.8, available / max(1, natural)))
headerHeight?.update(offset: header)
iconSize?.update(offset: diameter)
iconBackground.layer.cornerRadius = diameter / 2
textLeading?.update(offset: iconGap)
titleHeight?.update(offset: title)
messageTop?.update(offset: lines > 0 ? textGap : 0)
messageHeight?.update(offset: body)
indicatorTop?.update(offset: actionGap)
indicatorHeight?.update(offset: actionHeight)
indicatorButton.configuration?.titleTextAttributesTransformer = UIConfigurationTextAttributesTransformer { attributes in
var result = attributes
result.font = .systemFont(ofSize: compact ? 16 : 18, weight: .semibold)
result.foregroundColor = UIColor(hex: 0x4D91FF)
return result
}
}
}
@@ -6,7 +6,7 @@ import UIKit
final class DroneDockTaskStatusView: UIView {
/// 当前状态的主操作,由页面协调执行,不在组件中调用接口。
var onPrimaryAction: (() -> Void)?
/// 展开完整状态说明,由页面提供详情展示。
/// 点击失败原因区域时展开完整说明,由页面协调展示。
var onDetails: (() -> Void)?
/// 当前内容采用的字号和间距参考比例,始终介于 0.8 与 1。
private(set) var effectiveScale: CGFloat = 1
@@ -18,12 +18,15 @@ final class DroneDockTaskStatusView: UIView {
private let iconView = UIImageView()
private let titleLabel = DroneDockStyle.label(size: 22, weight: .semibold)
private let messageLabel = DroneDockStyle.label(size: 14, color: DroneDockStyle.secondary)
private let countdownLabel = DroneDockStyle.label(size: 13, weight: .medium, color: DroneDockStyle.primary)
private let deviceLabel = DroneDockStyle.label(size: 12, color: DroneDockStyle.secondary)
private let actionRow = UIView()
private let primaryButton = UIButton(type: .system)
private let detailsButton = UIButton(type: .system)
private let failureView = DroneDockTaskFailureView()
private let completedView = DroneDockTaskCompletedView()
private let shootingView = DroneDockTaskShootingView()
private var presentation: DroneDockTaskPresentation?
private var countdownSeconds: Int?
private var contentTop: Constraint?
private var contentLeading: Constraint?
private var contentTrailing: Constraint?
@@ -33,7 +36,7 @@ final class DroneDockTaskStatusView: UIView {
private var messageHeight: Constraint?
private var deviceHeight: Constraint?
/// 创建稳定的标题、说明、设备摘要与操作槽,所有状态复用同一组视图。
/// 创建固定状态槽,完成、失败与进行中使用各自的内容布局。
override init(frame: CGRect) {
super.init(frame: frame)
setupUI()
@@ -51,9 +54,30 @@ final class DroneDockTaskStatusView: UIView {
/// 更新真实状态与动作许可;刷新期间保留内容,只暂时禁用主操作。
func apply(_ presentation: DroneDockTaskPresentation, isRefreshing: Bool = false) {
self.presentation = presentation
updateCountdown(seconds: presentation.countdownSeconds)
let isFailure = presentation.phase == .failed
contentStack.isHidden = isFailure
let isCompleted = [.postShootUploading, .completed].contains(presentation.phase)
let isShooting = presentation.phase == .shooting
contentStack.isHidden = isFailure || isCompleted || isShooting
failureView.isHidden = !isFailure
completedView.isHidden = !isCompleted
shootingView.isHidden = !isShooting
completedView.setIdentifiersActive(isCompleted)
shootingView.setIdentifiersActive(isShooting)
titleLabel.accessibilityIdentifier = isCompleted || isShooting ? nil : "drone.task.remote.statusTitle"
messageLabel.accessibilityIdentifier = isCompleted || isShooting ? nil : "drone.task.remote.statusMessage"
if isShooting {
primaryButton.accessibilityIdentifier = nil
shootingView.apply(presentation)
setNeedsLayout()
return
}
if isCompleted {
primaryButton.accessibilityIdentifier = nil
completedView.apply(presentation, isRefreshing: isRefreshing)
setNeedsLayout()
return
}
if isFailure {
failureView.apply(presentation, isRefreshing: isRefreshing)
setNeedsLayout()
@@ -76,8 +100,33 @@ final class DroneDockTaskStatusView: UIView {
setNeedsLayout()
}
/// 只刷新已到达阶段的剩余秒数,不变更主操作、服务端阶段或执行任何回调。
func updateCountdown(seconds: Int?) {
let value = presentation?.phase == .ready ? seconds.map { max(0, $0) } : nil
guard value != countdownSeconds else { return }
let visibilityChanged = (value == nil) != (countdownSeconds == nil)
countdownSeconds = value
countdownLabel.text = value.map { "自动开拍倒计时:\($0) 秒" }
countdownLabel.isHidden = value == nil
if visibilityChanged { setNeedsLayout() }
}
/// 尺寸改变时仅重排内部内容,保留至少 44 点操作区域,不使用 transform 缩放。
override func layoutSubviews() {
if presentation?.phase == .shooting {
super.layoutSubviews()
shootingView.layoutIfNeeded()
effectiveScale = shootingView.effectiveScale
usesCompactLayout = shootingView.usesCompactLayout
return
}
if let phase = presentation?.phase, [.postShootUploading, .completed].contains(phase) {
super.layoutSubviews()
completedView.layoutIfNeeded()
effectiveScale = 1
usesCompactLayout = completedView.usesCompactLayout
return
}
if presentation?.phase == .failed {
super.layoutSubviews()
failureView.layoutIfNeeded()
@@ -91,6 +140,11 @@ final class DroneDockTaskStatusView: UIView {
private func setupUI() {
backgroundColor = .white
addSubview(shootingView)
shootingView.isHidden = true
addSubview(completedView)
completedView.isHidden = true
completedView.onViewMaterials = { [weak self] in self?.onPrimaryAction?() }
addSubview(failureView)
failureView.isHidden = true
failureView.onDetails = { [weak self] in self?.onDetails?() }
@@ -101,6 +155,7 @@ final class DroneDockTaskStatusView: UIView {
addSubview(contentStack)
contentStack.addArrangedSubview(titleRow)
contentStack.addArrangedSubview(messageLabel)
contentStack.addArrangedSubview(countdownLabel)
contentStack.addArrangedSubview(deviceLabel)
contentStack.addArrangedSubview(actionRow)
titleRow.addSubview(iconView)
@@ -113,28 +168,25 @@ final class DroneDockTaskStatusView: UIView {
messageLabel.numberOfLines = 3
messageLabel.lineBreakMode = .byTruncatingTail
messageLabel.accessibilityIdentifier = "drone.task.remote.statusMessage"
countdownLabel.font = .monospacedDigitSystemFont(ofSize: 13, weight: .medium)
countdownLabel.numberOfLines = 1
countdownLabel.isHidden = true
countdownLabel.accessibilityIdentifier = "drone.task.remote.countdown"
deviceLabel.numberOfLines = 1
deviceLabel.lineBreakMode = .byTruncatingTail
deviceLabel.accessibilityIdentifier = "drone.task.remote.deviceStatus"
actionRow.addSubview(primaryButton)
actionRow.addSubview(detailsButton)
primaryButton.layer.cornerRadius = 9
primaryButton.titleLabel?.font = .systemFont(ofSize: 15, weight: .semibold)
primaryButton.titleLabel?.lineBreakMode = .byTruncatingTail
primaryButton.setTitleColor(.white, for: .normal)
primaryButton.setTitleColor(.white.withAlphaComponent(0.9), for: .disabled)
primaryButton.addTarget(self, action: #selector(primaryTapped), for: .touchUpInside)
detailsButton.setTitle("详情", for: .normal)
detailsButton.setTitleColor(DroneDockStyle.primary, for: .normal)
detailsButton.titleLabel?.font = .systemFont(ofSize: 13, weight: .medium)
detailsButton.backgroundColor = DroneDockStyle.background
detailsButton.layer.cornerRadius = 9
detailsButton.accessibilityIdentifier = "drone.task.remote.details"
detailsButton.accessibilityLabel = "查看完整任务状态"
detailsButton.addTarget(self, action: #selector(detailsTapped), for: .touchUpInside)
}
private func setupConstraints() {
shootingView.snp.makeConstraints { $0.edges.equalToSuperview() }
completedView.snp.makeConstraints { $0.edges.equalToSuperview() }
failureView.snp.makeConstraints { make in make.edges.equalToSuperview() }
contentStack.snp.makeConstraints { make in
contentTop = make.top.equalToSuperview().offset(12).constraint
@@ -151,23 +203,20 @@ final class DroneDockTaskStatusView: UIView {
make.trailing.centerY.equalToSuperview()
}
messageLabel.snp.makeConstraints { make in messageHeight = make.height.equalTo(34).priority(999).constraint }
countdownLabel.snp.makeConstraints { make in make.height.equalTo(ceil(countdownLabel.font.lineHeight)).priority(999) }
deviceLabel.snp.makeConstraints { make in deviceHeight = make.height.equalTo(16).priority(999).constraint }
actionRow.snp.makeConstraints { make in make.height.equalTo(44) }
detailsButton.snp.makeConstraints { make in
make.top.trailing.bottom.equalToSuperview()
make.width.equalTo(64)
}
primaryButton.snp.makeConstraints { make in
make.top.leading.bottom.equalToSuperview()
make.trailing.equalTo(detailsButton.snp.leading).offset(-8)
make.edges.equalToSuperview()
}
}
private func updateContentLayout() {
guard let presentation, bounds.width > 0, bounds.height > 0 else { return }
let isExtreme = bounds.height < 120
let hasCountdown = countdownSeconds != nil
let horizontalInset: CGFloat = isExtreme ? 12 : 16
let verticalInset: CGFloat = isExtreme ? 6 : 12
let verticalInset: CGFloat = isExtreme ? (hasCountdown ? 4 : 6) : 12
let width = max(1, bounds.width - horizontalInset * 2)
let availableHeight = max(1, bounds.height - verticalInset * 2)
let message = DroneDockHomeMetric.usableText(presentation.message)
@@ -179,18 +228,20 @@ final class DroneDockTaskStatusView: UIView {
width: width - 46, lines: 2))
let naturalMessage = hasMessage ? Self.textHeight(message, font: .systemFont(ofSize: 14), width: width, lines: 3) : 0
let naturalDevice = hasDevice ? UIFont.systemFont(ofSize: 12).lineHeight : 0
let naturalGaps = CGFloat(1 + (hasMessage ? 1 : 0) + (hasDevice ? 1 : 0)) * 10
let naturalHeight = naturalTitle + naturalMessage + naturalDevice + 44 + naturalGaps
let countdownTextHeight = hasCountdown ? ceil(countdownLabel.font.lineHeight) : 0
let naturalGaps = CGFloat(1 + (hasMessage ? 1 : 0) + (hasDevice ? 1 : 0) + (hasCountdown ? 1 : 0)) * 10
let naturalHeight = naturalTitle + naturalMessage + countdownTextHeight + naturalDevice + 44 + naturalGaps
effectiveScale = min(1, max(0.8, availableHeight / max(1, naturalHeight)))
usesCompactLayout = bounds.height < 190 || naturalHeight * effectiveScale > availableHeight
// 先收紧图标和间距;只有不足九成空间时才缩小文字。
let fontScale: CGFloat = effectiveScale >= 0.9 ? 1 : effectiveScale / 0.9
titleLabel.font = .systemFont(ofSize: max(17, 22 * fontScale), weight: .semibold)
titleLabel.font = .systemFont(ofSize: isExtreme && hasCountdown ? 17 : max(17, 22 * fontScale), weight: .semibold)
messageLabel.font = .systemFont(ofSize: max(12, 14 * fontScale))
deviceLabel.font = .systemFont(ofSize: 12)
let icon: CGFloat = isExtreme ? 20 : usesCompactLayout ? 24 : 36 * effectiveScale
let gap: CGFloat = isExtreme ? 4 : max(4, 10 * effectiveScale)
let gap: CGFloat = isExtreme ? (hasCountdown ? 2 : 4)
: hasCountdown && usesCompactLayout ? 6 : max(4, 10 * effectiveScale)
let titleGap: CGFloat = usesCompactLayout ? 8 : 10 * effectiveScale
titleLabel.numberOfLines = usesCompactLayout ? 1 : 2
messageLabel.numberOfLines = usesCompactLayout ? 2 : 3
@@ -204,8 +255,8 @@ final class DroneDockTaskStatusView: UIView {
width: width, lines: messageLineCount)
let deviceTextHeight = deviceLabel.isHidden ? 0 : ceil(deviceLabel.font.lineHeight)
var contentHeight: CGFloat {
titleHeight + bodyHeight + deviceTextHeight + 44
+ CGFloat(1 + (messageLabel.isHidden ? 0 : 1) + (deviceLabel.isHidden ? 0 : 1)) * gap
titleHeight + bodyHeight + countdownTextHeight + deviceTextHeight + 44
+ CGFloat(1 + (messageLabel.isHidden ? 0 : 1) + (deviceLabel.isHidden ? 0 : 1) + (hasCountdown ? 1 : 0)) * gap
}
while contentHeight > availableHeight && messageLineCount > 1 && !messageLabel.isHidden {
messageLineCount -= 1
@@ -246,7 +297,8 @@ final class DroneDockTaskStatusView: UIView {
case .navigating: ("paperplane.fill", DroneDockStyle.primary)
case .ready: ("checkmark.circle.fill", DroneDockStyle.success)
case .shooting: ("video.fill", DroneDockStyle.primary)
case .postShootUploading: ("icloud.and.arrow.up", DroneDockStyle.primary)
case .postShootUploading: ("checkmark.circle.fill", DroneDockStyle.success)
case .postShootUploadFailed: ("exclamationmark.circle.fill", DroneDockStyle.warning)
case .paused: ("pause.circle.fill", DroneDockStyle.warning)
case .returning: ("arrow.uturn.backward.circle.fill", DroneDockStyle.warning)
case .completed: ("checkmark.circle.fill", DroneDockStyle.success)
@@ -261,5 +313,4 @@ final class DroneDockTaskStatusView: UIView {
onPrimaryAction?()
}
@objc private func detailsTapped() { onDetails?() }
}
@@ -0,0 +1,99 @@
import UIKit
@preconcurrency import VolcEngineRTC
/// 接收端最小能力,隔离测试无需初始化 SDK 或使用真实凭证。
@MainActor
protocol DroneDockRTCReceivingEngine: AnyObject {
/// 创建一个独立接收房间并转交事件。
func makeRoom(_ id: String, onEvent: @escaping @Sendable (DroneDockVolcEvent) -> Void) -> (any DroneDockRTCReceivingRoom)?
/// 按 SDK 提供的流 ID 绑定或解绑画布。
func setVideoView(_ view: UIView?, streamID: String) -> Int
/// 销毁引擎及本地接收资源。
func destroy()
}
/// 单路只收视频的房间;不提供发布、采集或设备控制能力。
@MainActor
protocol DroneDockRTCReceivingRoom: AnyObject {
/// 使用与当前用户匹配的凭证入房。
func join(_ configuration: DroneDockVolcLiveConfiguration) -> Int
/// 同用户凭证续期。
func updateToken(_ token: String) -> Int
/// 订阅或取消订阅远端视频。
func subscribeVideo(_ streamID: String, subscribe: Bool) -> Int
/// 退出并销毁接收房间。
func destroy()
}
/// 火山 SDK 适配器;真实创建点再次拦截 Debug,测试不能通过注入绕开保护。
@MainActor
final class DroneDockVolcEngineAdapter: DroneDockRTCReceivingEngine {
private let engine: ByteRTCEngine
private let delegate: DroneDockVolcDelegate
private init(engine: ByteRTCEngine, delegate: DroneDockVolcDelegate) {
self.engine = engine
self.delegate = delegate
}
/// 仅在构建策略允许真实图传时构造 SDK。
static func make(appID: String, onEvent: @escaping @Sendable (DroneDockVolcEvent) -> Void) -> (any DroneDockRTCReceivingEngine)? {
guard !DeviceCommandDebugPolicy.blocksLiveRequests else { return nil }
let delegate = DroneDockVolcDelegate(emit: onEvent)
let config = ByteRTCEngineConfig()
config.appID = appID
guard let engine = ByteRTCEngine.createRTCEngine(config, delegate: delegate) else { return nil }
return DroneDockVolcEngineAdapter(engine: engine, delegate: delegate)
}
/// 每个房间独立保留回调桥接,避免弱引用导致事件丢失。
func makeRoom(_ id: String, onEvent: @escaping @Sendable (DroneDockVolcEvent) -> Void) -> (any DroneDockRTCReceivingRoom)? {
guard let room = engine.createRTCRoom(id) else { return nil }
return DroneDockVolcRoomAdapter(room: room, delegate: DroneDockVolcDelegate(emit: onEvent))
}
/// 画布只依赖发布回调的 streamID,不假定远端流索引为零。
func setVideoView(_ view: UIView?, streamID: String) -> Int {
let canvas = ByteRTCVideoCanvas()
canvas.view = view
canvas.renderMode = .fit
return Int(engine.setRemoteVideoCanvas(streamID, withCanvas: canvas))
}
/// 房间由接收器先释放,再销毁共享引擎。
func destroy() {
engine.delegate = nil
ByteRTCEngine.destroyRTCEngine()
}
}
/// 将只收视频的房间配置封装在 SDK 边界,所有回调由接收器切回主线程。
@MainActor
private final class DroneDockVolcRoomAdapter: DroneDockRTCReceivingRoom {
private let room: ByteRTCRoom
private let delegate: DroneDockVolcDelegate
init(room: ByteRTCRoom, delegate: DroneDockVolcDelegate) {
self.room = room
self.delegate = delegate
room.setRTCRoomDelegate(delegate)
}
func join(_ configuration: DroneDockVolcLiveConfiguration) -> Int {
let config = ByteRTCRoomConfig()
config.isPublishAudio = false
config.isPublishVideo = false
config.isAutoSubscribeAudio = false
config.isAutoSubscribeVideo = false
let user = ByteRTCUserInfo()
user.userId = configuration.userID
return Int(room.joinRoom(configuration.token, userInfo: user, userVisibility: false, roomConfig: config))
}
func updateToken(_ token: String) -> Int { Int(room.updateToken(token)) }
func subscribeVideo(_ streamID: String, subscribe: Bool) -> Int { Int(room.subscribeStreamVideo(streamID, subscribe: subscribe)) }
func destroy() {
room.setRTCRoomDelegate(nil)
room.destroy()
}
}
@@ -11,11 +11,37 @@ protocol DroneDockLivePlaying: AnyObject {
func stop()
}
/// 一个 RTC 引擎接收两个房间,机巢先接入,无人机有帧后覆盖,停流后恢复机巢。
/// 真实 SDK 入口始终执行编译期禁飞保护,没有运行时放行参数。
@MainActor
final class DroneDockVolcLivePlayer: DroneDockLivePlaying {
private var engine: ByteRTCEngine?
private var delegate: DroneDockVolcDelegate?
private let receiver = DroneDockLiveReceiver(makeEngine: DroneDockVolcEngineAdapter.make)
/// Release 通过接收器播放;Debug 在创建 SDK 之前拒绝连接。
func start(_ configurations: [DroneDockVolcLiveConfiguration], in view: UIView,
onEvent: @escaping @MainActor (DroneDockLivePlaybackEvent) -> Void) {
guard !DeviceCommandDebugPolicy.blocksLiveRequests else {
stop(); onEvent(.failed(DeviceCommandDebugPolicy.blockedMessage)); return
}
receiver.start(configurations, in: view, onEvent: onEvent)
}
/// 释放本机播放资源,不发送任何设备控制请求。
func stop() { receiver.stop() }
}
/// 一个 RTC 引擎接收两个房间,机巢先接入,无人机有帧后覆盖,停流后恢复机巢。
@MainActor
final class DroneDockLiveReceiver: DroneDockLivePlaying {
private var engine: (any DroneDockRTCReceivingEngine)?
private let makeEngine: (String, @escaping @Sendable (DroneDockVolcEvent) -> Void) -> (any DroneDockRTCReceivingEngine)?
private let firstFrameDelay: @Sendable () async throws -> Void
/// 生产环境注入带 Debug 保护的适配器;测试只注入内存接收端。
init(makeEngine: @escaping (String, @escaping @Sendable (DroneDockVolcEvent) -> Void) -> (any DroneDockRTCReceivingEngine)?,
firstFrameDelay: @escaping @Sendable () async throws -> Void = { try await Task.sleep(for: .seconds(20)) }) {
self.makeEngine = makeEngine
self.firstFrameDelay = firstFrameDelay
}
private weak var container: UIView?
private var sources: [String: DroneDockVolcSource] = [:]
private var configurations: [DroneDockVolcLiveConfiguration] = []
@@ -29,9 +55,6 @@ final class DroneDockVolcLivePlayer: DroneDockLivePlaying {
/// 加入只收视频的房间;同一来源只更新 Token,避免后台重查导致画面闪断。
func start(_ configurations: [DroneDockVolcLiveConfiguration], in view: UIView,
onEvent: @escaping @MainActor (DroneDockLivePlaybackEvent) -> Void) {
guard !DeviceCommandDebugPolicy.blocksLiveRequests else {
stop(); onEvent(.failed(DeviceCommandDebugPolicy.blockedMessage)); return
}
guard let first = configurations.first else { stop(); return }
if container !== view || self.configurations.first?.appID != first.appID { stop() }
self.onEvent = onEvent
@@ -39,16 +62,12 @@ final class DroneDockVolcLivePlayer: DroneDockLivePlaying {
self.configurations = configurations
if engine == nil {
let generation = generation
let delegate = DroneDockVolcDelegate { [weak self] event in
guard let engine = makeEngine(first.appID, { [weak self] event in
Task { @MainActor [weak self] in
guard let self, self.generation == generation else { return }
self.receive(event)
}
}
self.delegate = delegate
let config = ByteRTCEngineConfig()
config.appID = first.appID
guard let engine = ByteRTCEngine.createRTCEngine(config, delegate: delegate) else {
}) else {
stop(); onEvent(.failed("图传播放器初始化失败")); return
}
self.engine = engine
@@ -74,10 +93,8 @@ final class DroneDockVolcLivePlayer: DroneDockLivePlaying {
generation = UUID()
onEvent = nil
for role in Array(sources.keys) { removeSource(role) }
engine?.delegate = nil
if engine != nil { ByteRTCEngine.destroyRTCEngine() }
engine?.destroy()
engine = nil
delegate = nil
container = nil
configurations = []
selection = DroneDockLiveSourceSelection()
@@ -105,7 +122,15 @@ final class DroneDockVolcLivePlayer: DroneDockLivePlaying {
scheduleExpiry(source)
return
}
guard let container, let room = engine?.createRTCRoom(configuration.roomID) else {
guard let container else { return }
let generation = generation
let sourceID = UUID()
guard let room = engine?.makeRoom(configuration.roomID, onEvent: { [weak self] event in
Task { @MainActor [weak self] in
guard let self, self.generation == generation, self.sources[role]?.id == sourceID else { return }
self.receive(event)
}
}) else {
failedRoles.insert(role)
if role == "airport" { allowsDroneConnection = true }
return
@@ -115,25 +140,9 @@ final class DroneDockVolcLivePlayer: DroneDockLivePlaying {
view.backgroundColor = .black
view.isHidden = true
container.addSubview(view)
let generation = generation
let sourceID = UUID()
let delegate = DroneDockVolcDelegate { [weak self] event in
Task { @MainActor [weak self] in
guard let self, self.generation == generation, self.sources[role]?.id == sourceID else { return }
self.receive(event)
}
}
let source = DroneDockVolcSource(id: sourceID, configuration: configuration, room: room, view: view, delegate: delegate)
let source = DroneDockVolcSource(id: sourceID, configuration: configuration, room: room, view: view)
sources[role] = source
room.setRTCRoomDelegate(delegate)
let roomConfig = ByteRTCRoomConfig()
roomConfig.isPublishAudio = false
roomConfig.isPublishVideo = false
roomConfig.isAutoSubscribeAudio = false
roomConfig.isAutoSubscribeVideo = false
let user = ByteRTCUserInfo()
user.userId = configuration.userID
let result = room.joinRoom(configuration.token, userInfo: user, userVisibility: false, roomConfig: roomConfig)
let result = room.join(configuration)
guard result == 0 else {
removeSource(role)
failedRoles.insert(role)
@@ -141,10 +150,12 @@ final class DroneDockVolcLivePlayer: DroneDockLivePlaying {
return
}
// 机巢无首帧时不能无限等待,仍尝试无人机;已连房间继续等待发布事件。
let delay = firstFrameDelay
source.timeoutTask = Task { @MainActor [weak self] in
try? await Task.sleep(for: .seconds(20))
do { try await delay() } catch { return }
guard !Task.isCancelled, let self, self.generation == generation, self.sources[role]?.id == sourceID else { return }
self.sourceFailed(role)
// 首帧等待超时只开放另一路;不能销毁仍在等待发布的房间或取消补取参数。
self.markReady(false, source: source)
}
scheduleExpiry(source)
}
@@ -163,6 +174,11 @@ final class DroneDockVolcLivePlayer: DroneDockLivePlaying {
guard !Task.isCancelled, let self, self.generation == generation, self.sources[role]?.id == sourceID else { return }
self.removeSource(role)
self.displaySelectedSource()
if self.sources.isEmpty {
let callback = self.onEvent
self.stop()
callback?(.expired)
}
}
}
@@ -171,32 +187,28 @@ final class DroneDockVolcLivePlayer: DroneDockLivePlaying {
guard let source = sources.removeValue(forKey: role) else { return }
source.timeoutTask?.cancel()
source.expiryTask?.cancel()
if let streamID = source.streamID { engine?.setRemoteVideoCanvas(streamID, withCanvas: nil) }
source.room.setRTCRoomDelegate(nil)
if let streamID = source.streamID { _ = engine?.setVideoView(nil, streamID: streamID) }
source.room.destroy()
source.view.removeFromSuperview()
}
private func receive(_ event: DroneDockVolcEvent) {
switch event {
case .published(let id, let roomID, let index, let published):
guard index == 0, let source = source(in: roomID) else { return }
case .published(let id, let roomID, let published):
guard !id.isEmpty, let source = source(in: roomID) else { return }
if !published {
guard source.streamID == id else { return }
engine?.setRemoteVideoCanvas(id, withCanvas: nil)
source.room.subscribeStreamVideo(id, subscribe: false)
_ = engine?.setVideoView(nil, streamID: id)
_ = source.room.subscribeVideo(id, subscribe: false)
source.streamID = nil
markReady(false, source: source)
return
}
guard source.streamID == nil else { return }
source.streamID = id
let canvas = ByteRTCVideoCanvas()
canvas.view = source.view
canvas.renderMode = .fit
let render = engine?.setRemoteVideoCanvas(id, withCanvas: canvas)
let subscribe = source.room.subscribeStreamVideo(id, subscribe: true)
if render != 0 || subscribe != 0 { sourceFailed(source.configuration.role) }
let render = engine?.setVideoView(source.view, streamID: id)
let subscribe = source.room.subscribeVideo(id, subscribe: true)
if render != 0 || subscribe != 0 { sourceFailed(source.configuration.role, message: "图传订阅失败(\(render ?? -1)/\(subscribe)),请重试") }
case .frame(let id, let roomID):
guard let source = source(in: roomID), source.streamID == id else { return }
markReady(true, source: source)
@@ -207,9 +219,9 @@ final class DroneDockVolcLivePlayer: DroneDockLivePlaying {
case .stopped, .frozen, .failed: markReady(false, source: source)
default: break
}
case .roomFailed(let roomID):
case .roomFailed(let roomID, let code):
guard let source = source(in: roomID) else { return }
sourceFailed(source.configuration.role)
sourceFailed(source.configuration.role, message: "图传入房失败(\(code)),请重试")
case .connectionLost:
for source in sources.values { selection.setReady(false, role: source.configuration.role) }
displaySelectedSource()
@@ -237,7 +249,7 @@ final class DroneDockVolcLivePlayer: DroneDockLivePlaying {
}
}
private func sourceFailed(_ role: String) {
private func sourceFailed(_ role: String, message: String) {
failedRoles.insert(role)
selection.setReady(false, role: role)
if role == "airport" { allowsDroneConnection = true; connectDroneIfAllowed() }
@@ -245,7 +257,7 @@ final class DroneDockVolcLivePlayer: DroneDockLivePlaying {
if selection.selectedRole == nil, Set(configurations.map(\.role)).isSubset(of: failedRoles) {
let callback = onEvent
stop()
callback?(.failed("暂未收到可用的图传画面,请重试"))
callback?(.failed(message))
}
}
@@ -264,39 +276,38 @@ final class DroneDockVolcLivePlayer: DroneDockLivePlaying {
private final class DroneDockVolcSource {
let id: UUID
var configuration: DroneDockVolcLiveConfiguration
let room: ByteRTCRoom
let room: any DroneDockRTCReceivingRoom
let view: UIView
let delegate: DroneDockVolcDelegate
var streamID: String?
var timeoutTask: Task<Void, Never>?
var expiryTask: Task<Void, Never>?
init(id: UUID, configuration: DroneDockVolcLiveConfiguration, room: ByteRTCRoom, view: UIView, delegate: DroneDockVolcDelegate) {
self.id = id; self.configuration = configuration; self.room = room; self.view = view; self.delegate = delegate
init(id: UUID, configuration: DroneDockVolcLiveConfiguration, room: any DroneDockRTCReceivingRoom, view: UIView) {
self.id = id; self.configuration = configuration; self.room = room; self.view = view
}
}
/// SDK 工作线程只转交值类型事件;事件带房间和流身份以隔离两路回调。
private enum DroneDockVolcEvent: Sendable {
case published(String, String, Int, Bool)
enum DroneDockVolcEvent: Sendable {
case published(String, String, Bool)
case frame(String, String)
case videoState(String, String, ByteRTCRemoteVideoState)
case roomFailed(String)
case roomFailed(String, Int)
case connectionLost
case failed(Int)
}
/// SDK 回调桥接,不采集音视频,不处理设备控制消息。
private final class DroneDockVolcDelegate: NSObject, ByteRTCEngineDelegate, ByteRTCRoomDelegate {
final class DroneDockVolcDelegate: NSObject, ByteRTCEngineDelegate, ByteRTCRoomDelegate {
private let emit: @Sendable (DroneDockVolcEvent) -> Void
init(emit: @escaping @Sendable (DroneDockVolcEvent) -> Void) { self.emit = emit }
func rtcRoom(_ rtcRoom: ByteRTCRoom, onUserPublishStreamVideo streamId: String, info: ByteRTCStreamInfo, isPublish: Bool) {
emit(.published(streamId, info.roomId, info.streamIndex, isPublish))
emit(.published(streamId, info.roomId, isPublish))
}
func rtcRoom(_ rtcRoom: ByteRTCRoom, onRoomStateChanged roomId: String, withUid uid: String, state: Int, extraInfo: String) {
if state != 0 { emit(.roomFailed(roomId)) }
if state != 0 { emit(.roomFailed(roomId, state)) }
}
func rtcEngine(_ engine: ByteRTCEngine, onFirstRemoteVideoFrameDecoded streamId: String,