feat(drone-dock): 实现局域网扫码直传交付
This commit is contained in:
@@ -21,12 +21,12 @@ final class DroneDeliveryUploadViewController: BaseViewController {
|
||||
weak var delegate: DroneDeliveryUploadViewControllerDelegate?
|
||||
|
||||
/// 页面阶段只管理展示导航,不参与上传成功或拍摄次数计算。
|
||||
private enum Phase: Equatable { case method, nearby, point, picker, queue }
|
||||
private enum Phase: Equatable { case method, point, picker, queue }
|
||||
/// 队列摘要与主体使用独立分区。
|
||||
private enum Section: Hashable { case summary, content }
|
||||
/// 每一项依靠稳定业务身份更新,选择与进度不改变 Diffable 标识。
|
||||
private enum Item: Hashable {
|
||||
case nearbyMethod, cloudMethod, nearbyMessage, point(String), video(String), upload(String), summary, empty
|
||||
case nearbyMethod, cloudMethod, point(String), video(String), upload(String), summary, empty
|
||||
}
|
||||
|
||||
private var phase: Phase
|
||||
@@ -53,6 +53,7 @@ final class DroneDeliveryUploadViewController: BaseViewController {
|
||||
/// 返回前台或结束预览后只刷新本地状态,不自动启动暂停队列。
|
||||
override func viewWillAppear(_ animated: Bool) {
|
||||
super.viewWillAppear(animated)
|
||||
navigationController?.setNavigationBarHidden(true, animated: false)
|
||||
viewModel.refresh()
|
||||
if dataSource != nil { applySnapshot(animated: false) }
|
||||
}
|
||||
@@ -145,7 +146,6 @@ final class DroneDeliveryUploadViewController: BaseViewController {
|
||||
let height: CGFloat
|
||||
switch self.phase {
|
||||
case .method: height = 88
|
||||
case .nearby: height = 170
|
||||
case .point: height = self.viewModel.points.isEmpty ? 180 : 52
|
||||
case .picker: height = 180
|
||||
case .queue: height = self.viewModel.batch?.items.isEmpty == false ? 82 : 180
|
||||
@@ -174,7 +174,7 @@ final class DroneDeliveryUploadViewController: BaseViewController {
|
||||
case .nearbyMethod, .cloudMethod:
|
||||
let cell = list.dequeueReusableCell(withReuseIdentifier: "method", for: indexPath) as! DroneDeliveryUploadMethodCell
|
||||
if item == .nearbyMethod {
|
||||
cell.apply(title: "面对面闪传", detail: "近距离传给游客 · 流程待确认", symbol: "wifi",
|
||||
cell.apply(title: "面对面闪传", detail: "同一 Wi-Fi 扫码接收 · 无需上传", symbol: "wifi",
|
||||
identifier: "drone.delivery.upload.method.nearby")
|
||||
} else {
|
||||
cell.apply(title: "云端上传", detail: "选择打卡点,演示上传成片", symbol: "icloud.and.arrow.up",
|
||||
@@ -215,11 +215,9 @@ final class DroneDeliveryUploadViewController: BaseViewController {
|
||||
self.delegate?.deliveryUploadViewControllerDidRequestReview(self)
|
||||
}
|
||||
return cell
|
||||
case .nearbyMessage, .empty:
|
||||
case .empty:
|
||||
let cell = list.dequeueReusableCell(withReuseIdentifier: "message", for: indexPath) as! DroneDeliveryUploadMessageCell
|
||||
if item == .nearbyMessage {
|
||||
cell.apply(title: "闪传流程待确认", detail: "热点连接与游客接收流程暂未接入。\n现在可以先体验云端演示上传。", symbol: "wifi")
|
||||
} else if self.phase == .point {
|
||||
if self.phase == .point {
|
||||
cell.apply(title: "暂无可交付点位", detail: "当前订单没有可用点位,请稍后重试。", symbol: "mappin.slash.circle")
|
||||
} else if self.phase == .picker {
|
||||
cell.apply(title: "暂无可选演示视频", detail: "本点位的示例视频已交付,可返回选择其他点位。", symbol: "video.slash")
|
||||
@@ -256,7 +254,6 @@ final class DroneDeliveryUploadViewController: BaseViewController {
|
||||
let items: [Item]
|
||||
switch phase {
|
||||
case .method: items = [.nearbyMethod, .cloudMethod]
|
||||
case .nearby: items = [.nearbyMessage]
|
||||
case .point: items = viewModel.points.isEmpty ? [.empty] : viewModel.points.map { .point($0.id) }
|
||||
case .picker: items = viewModel.availableVideos.isEmpty ? [.empty] : viewModel.availableVideos.map { .video($0.id) }
|
||||
case .queue: items = uploadItems.isEmpty ? [.empty] : uploadItems.map { .upload($0.id) }
|
||||
@@ -276,9 +273,6 @@ final class DroneDeliveryUploadViewController: BaseViewController {
|
||||
case .method:
|
||||
headerView.apply(title: "交付成片", customer: customer, detail: "请选择本次交付方式")
|
||||
footerView.apply(primaryTitle: nil, enabled: false, identifier: "", detail: "可分批演示交付多个作品,不影响拍摄次数", secondaryTitle: nil)
|
||||
case .nearby:
|
||||
headerView.apply(title: "面对面闪传", customer: customer, detail: "本次仅展示交付入口")
|
||||
footerView.apply(primaryTitle: "改用云端上传", enabled: true, identifier: "drone.delivery.upload.useCloud", detail: "", secondaryTitle: "返回交付方式")
|
||||
case .point:
|
||||
headerView.apply(title: "选择打卡点", customer: customer, detail: "云端上传 · 请选择本批成片对应的打卡点")
|
||||
footerView.apply(primaryTitle: "去演示相册选视频", enabled: viewModel.selectedPoint != nil && !viewModel.isUploadLocked,
|
||||
@@ -320,7 +314,6 @@ final class DroneDeliveryUploadViewController: BaseViewController {
|
||||
private func primaryTapped() {
|
||||
switch phase {
|
||||
case .method: break
|
||||
case .nearby: openCloudFlow()
|
||||
case .point: if viewModel.selectedPoint != nil { showPhase(.picker) }
|
||||
case .picker:
|
||||
if viewModel.startUpload() { showPhase(.queue); startDemoUpload() }
|
||||
@@ -338,6 +331,25 @@ final class DroneDeliveryUploadViewController: BaseViewController {
|
||||
}
|
||||
}
|
||||
|
||||
/// 演示入口也使用同一局域网页面,但必须显式选择本机视频才会开放传输。
|
||||
private func openNearbyFlow() {
|
||||
let nearby = DroneDockNearbyTransferViewController(customerTitle: "面对面交付")
|
||||
if let navigation = navigationController {
|
||||
nearby.onClose = { [weak navigation] in navigation?.popViewController(animated: true) }
|
||||
navigation.sheetPresentationController?.animateChanges {
|
||||
navigation.sheetPresentationController?.selectedDetentIdentifier = .large
|
||||
}
|
||||
navigation.setNavigationBarHidden(false, animated: true)
|
||||
navigation.pushViewController(nearby, animated: true)
|
||||
} else {
|
||||
let navigation = UINavigationController(rootViewController: nearby)
|
||||
navigation.modalPresentationStyle = .pageSheet
|
||||
navigation.sheetPresentationController?.detents = [.large()]
|
||||
nearby.onClose = { [weak navigation] in navigation?.dismiss(animated: true) }
|
||||
present(navigation, animated: true)
|
||||
}
|
||||
}
|
||||
|
||||
/// 选择云端仅恢复原队列或进入选点,不清除批次,也不自动继续上传。
|
||||
private func openCloudFlow() {
|
||||
showPhase(viewModel.batch == nil ? .point : .queue)
|
||||
@@ -346,7 +358,7 @@ final class DroneDeliveryUploadViewController: BaseViewController {
|
||||
private func secondaryTapped() {
|
||||
switch phase {
|
||||
case .method: break
|
||||
case .nearby, .point: showPhase(.method)
|
||||
case .point: showPhase(.method)
|
||||
case .picker: showPhase(.point)
|
||||
case .queue: finish()
|
||||
}
|
||||
@@ -402,7 +414,7 @@ extension DroneDeliveryUploadViewController: UICollectionViewDelegate {
|
||||
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
|
||||
guard let item = dataSource.itemIdentifier(for: indexPath) else { return }
|
||||
switch item {
|
||||
case .nearbyMethod: showPhase(.nearby)
|
||||
case .nearbyMethod: openNearbyFlow()
|
||||
case .cloudMethod: openCloudFlow()
|
||||
case .point(let id): viewModel.selectPoint(id: id); applySnapshot(animated: true)
|
||||
case .upload(let id):
|
||||
|
||||
@@ -13,6 +13,18 @@ enum DroneDockDeliveryEntry {
|
||||
navigation.modalPresentationStyle = .pageSheet
|
||||
navigation.onDidCloseCloud = onDidCloseCloud
|
||||
methods.onClose = { [weak navigation] in navigation?.dismiss(animated: true) }
|
||||
methods.onNearbyTransfer = { [weak navigation, weak methods] in
|
||||
guard let navigation, let methods, navigation.topViewController === methods else { return }
|
||||
let nearby = DroneDockNearbyTransferViewController(customerTitle: order.touristTitle)
|
||||
nearby.onClose = { [weak navigation] in navigation?.dismiss(animated: true) }
|
||||
navigation.isModalInPresentation = true
|
||||
navigation.sheetPresentationController?.animateChanges {
|
||||
navigation.sheetPresentationController?.detents = [.large()]
|
||||
navigation.sheetPresentationController?.selectedDetentIdentifier = .large
|
||||
}
|
||||
navigation.setNavigationBarHidden(false, animated: true)
|
||||
navigation.pushViewController(nearby, animated: true)
|
||||
}
|
||||
methods.onCloudUpload = { [weak navigation, weak methods] in
|
||||
guard let navigation, let methods, navigation.topViewController === methods else { return }
|
||||
let cloud = controllerFactory(order, context, taskID)
|
||||
|
||||
@@ -1,26 +1,25 @@
|
||||
import SnapKit
|
||||
import UIKit
|
||||
|
||||
/// 真实订单的交付方式弹窗,只展示方式选择并将云端交付导航交回入口。
|
||||
/// 订单的交付方式弹窗,将云端交付和局域网闪传导航交回统一入口。
|
||||
@MainActor
|
||||
final class DroneDockDeliveryMethodViewController: BaseViewController {
|
||||
/// 用户选择云端上传后,由入口打开现有真实交付页。
|
||||
var onCloudUpload: (() -> Void)?
|
||||
/// 用户选择面对面闪传后,由入口打开独立本地传输页。
|
||||
var onNearbyTransfer: (() -> Void)?
|
||||
/// 用户关闭弹窗后,由入口统一结束当前模态流程。
|
||||
var onClose: (() -> Void)?
|
||||
|
||||
/// 闪传只显示未接入说明,不创建传输任务或连接设备。
|
||||
private enum Phase: Equatable { case methods, nearby }
|
||||
/// 两种交付方式与闪传说明使用独立、稳定的列表身份。
|
||||
private enum Item: Hashable { case nearby, cloud, nearbyMessage }
|
||||
/// 两种交付方式使用独立、稳定的列表身份。
|
||||
private enum Item: Hashable { case nearby, cloud }
|
||||
|
||||
private let customerTitle: String
|
||||
private let headerView = DroneDeliveryUploadHeaderView()
|
||||
private let footerView = DroneDeliveryUploadFooterView()
|
||||
private lazy var collectionView = UICollectionView(frame: .zero, collectionViewLayout: makeLayout())
|
||||
private var dataSource: UICollectionViewDiffableDataSource<Int, Item>!
|
||||
private var phase = Phase.methods
|
||||
private var hasRequestedCloud = false
|
||||
private var hasRequestedNavigation = false
|
||||
|
||||
/// 游客标题由选中的订单传入,本弹窗不读取网络或改变订单状态。
|
||||
init(customerTitle: String) {
|
||||
@@ -34,7 +33,7 @@ final class DroneDockDeliveryMethodViewController: BaseViewController {
|
||||
|
||||
override func viewWillAppear(_ animated: Bool) {
|
||||
super.viewWillAppear(animated)
|
||||
hasRequestedCloud = false
|
||||
hasRequestedNavigation = false
|
||||
navigationController?.isModalInPresentation = false
|
||||
isModalInPresentation = false
|
||||
navigationController?.setNavigationBarHidden(true, animated: false)
|
||||
@@ -54,7 +53,6 @@ final class DroneDockDeliveryMethodViewController: BaseViewController {
|
||||
collectionView.accessibilityIdentifier = "drone.delivery.method.list"
|
||||
collectionView.delegate = self
|
||||
collectionView.register(DroneDeliveryUploadMethodCell.self, forCellWithReuseIdentifier: "method")
|
||||
collectionView.register(DroneDeliveryUploadMessageCell.self, forCellWithReuseIdentifier: "message")
|
||||
[headerView, collectionView, footerView].forEach(view.addSubview)
|
||||
configureDataSource()
|
||||
applySnapshot(animated: false)
|
||||
@@ -76,7 +74,6 @@ final class DroneDockDeliveryMethodViewController: BaseViewController {
|
||||
override func bindActions() {
|
||||
headerView.onCloseTap = { [weak self] in self?.onClose?() }
|
||||
footerView.onPrimaryTap = { [weak self] in self?.requestCloudUpload() }
|
||||
footerView.onSecondaryTap = { [weak self] in self?.showPhase(.methods) }
|
||||
}
|
||||
|
||||
private func configureSheet() {
|
||||
@@ -93,14 +90,13 @@ final class DroneDockDeliveryMethodViewController: BaseViewController {
|
||||
}
|
||||
|
||||
private func makeLayout() -> UICollectionViewLayout {
|
||||
UICollectionViewCompositionalLayout { [weak self] _, _ in
|
||||
guard let self else { return nil }
|
||||
let height: CGFloat = self.phase == .methods ? 88 : 132
|
||||
UICollectionViewCompositionalLayout { _, _ in
|
||||
let height: CGFloat = 88
|
||||
let item = NSCollectionLayoutItem(layoutSize: .init(widthDimension: .fractionalWidth(1), heightDimension: .fractionalHeight(1)))
|
||||
let group = NSCollectionLayoutGroup.vertical(
|
||||
layoutSize: .init(widthDimension: .fractionalWidth(1), heightDimension: .absolute(height)), subitems: [item])
|
||||
let section = NSCollectionLayoutSection(group: group)
|
||||
section.interGroupSpacing = self.phase == .methods ? 12 : 0
|
||||
section.interGroupSpacing = 12
|
||||
section.contentInsets = .init(top: 4, leading: 20, bottom: 4, trailing: 20)
|
||||
return section
|
||||
}
|
||||
@@ -112,16 +108,11 @@ final class DroneDockDeliveryMethodViewController: BaseViewController {
|
||||
case .nearby, .cloud:
|
||||
let cell = collection.dequeueReusableCell(withReuseIdentifier: "method", for: path) as! DroneDeliveryUploadMethodCell
|
||||
if item == .nearby {
|
||||
cell.apply(title: "面对面闪传", detail: "近距离传给游客 · 流程待确认", symbol: "wifi", identifier: "drone.delivery.method.nearby")
|
||||
cell.apply(title: "面对面闪传", detail: "同一 Wi-Fi 扫码接收 · 无需上传", symbol: "wifi", identifier: "drone.delivery.method.nearby")
|
||||
} else {
|
||||
cell.apply(title: "云端上传", detail: "选择打卡点,上传后游客可查看", symbol: "icloud.and.arrow.up", identifier: "drone.delivery.method.cloud")
|
||||
}
|
||||
return cell
|
||||
case .nearbyMessage:
|
||||
let cell = collection.dequeueReusableCell(withReuseIdentifier: "message", for: path) as! DroneDeliveryUploadMessageCell
|
||||
cell.apply(title: "闪传流程待确认", detail: "热点连接与游客接收流程暂未接入。\n请使用云端上传交付成片。", symbol: "wifi")
|
||||
cell.accessibilityIdentifier = "drone.delivery.method.nearbyMessage"
|
||||
return cell
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -130,41 +121,30 @@ final class DroneDockDeliveryMethodViewController: BaseViewController {
|
||||
guard dataSource != nil else { return }
|
||||
var snapshot = NSDiffableDataSourceSnapshot<Int, Item>()
|
||||
snapshot.appendSections([0])
|
||||
switch phase {
|
||||
case .methods:
|
||||
headerView.apply(title: "交付成片", customer: customerTitle, detail: "请选择本次交付方式")
|
||||
footerView.apply(primaryTitle: nil, enabled: false, identifier: "", detail: "可分批交付多个作品,不影响拍摄次数", secondaryTitle: nil)
|
||||
snapshot.appendItems([.nearby, .cloud])
|
||||
case .nearby:
|
||||
headerView.apply(title: "面对面闪传", customer: customerTitle, detail: "本次仅展示交付入口")
|
||||
footerView.apply(primaryTitle: "改用云端上传", enabled: true, identifier: "drone.delivery.method.useCloud", detail: "", secondaryTitle: "返回交付方式")
|
||||
snapshot.appendItems([.nearbyMessage])
|
||||
}
|
||||
headerView.apply(title: "交付成片", customer: customerTitle, detail: "请选择本次交付方式")
|
||||
footerView.apply(primaryTitle: nil, enabled: false, identifier: "", detail: "可分批交付多个作品,不影响拍摄次数", secondaryTitle: nil)
|
||||
snapshot.appendItems([.nearby, .cloud])
|
||||
dataSource.apply(snapshot, animatingDifferences: animated)
|
||||
collectionView.collectionViewLayout.invalidateLayout()
|
||||
}
|
||||
|
||||
private func showPhase(_ phase: Phase) {
|
||||
self.phase = phase
|
||||
applySnapshot(animated: true)
|
||||
collectionView.setContentOffset(.zero, animated: false)
|
||||
}
|
||||
|
||||
private func requestCloudUpload() {
|
||||
guard !hasRequestedCloud, let onCloudUpload else { return }
|
||||
hasRequestedCloud = true
|
||||
guard !hasRequestedNavigation, let onCloudUpload else { return }
|
||||
hasRequestedNavigation = true
|
||||
onCloudUpload()
|
||||
}
|
||||
}
|
||||
|
||||
extension DroneDockDeliveryMethodViewController: UICollectionViewDelegate {
|
||||
/// 云端方式交回调用方,闪传方式只在当前弹窗展示待接入说明。
|
||||
/// 只在用户选择后进入对应流程,方式弹窗本身不读取网络。
|
||||
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
|
||||
guard let item = dataSource.itemIdentifier(for: indexPath), !hasRequestedCloud else { return }
|
||||
guard let item = dataSource.itemIdentifier(for: indexPath), !hasRequestedNavigation else { return }
|
||||
switch item {
|
||||
case .nearby: showPhase(.nearby)
|
||||
case .nearby:
|
||||
guard let onNearbyTransfer else { return }
|
||||
hasRequestedNavigation = true
|
||||
onNearbyTransfer()
|
||||
case .cloud: requestCloudUpload()
|
||||
case .nearbyMessage: break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,464 @@
|
||||
import AVKit
|
||||
import SnapKit
|
||||
import UIKit
|
||||
|
||||
/// 单个本地视频的局域网扫码交付页,游客无需安装 App。
|
||||
@MainActor
|
||||
final class DroneDockNearbyTransferViewController: BaseViewController {
|
||||
/// 同一页面供订单和素材库入口复用,不依赖云端交付状态。
|
||||
let viewModel: DroneDockNearbyTransferViewModel
|
||||
/// 在交付弹窗中关闭整个流程,由调用方决定如何退出。
|
||||
var onClose: (() -> Void)?
|
||||
|
||||
private let customerTitle: String
|
||||
private let videoPicker: (@MainActor () async throws -> DroneDockDeliveryVideo?)?
|
||||
private var operationTask: Task<Void, Never>?
|
||||
private var metadataTask: Task<Void, Never>?
|
||||
private var isPicking = false
|
||||
private var pickerError: String?
|
||||
private var ownedVideoURLs: Set<URL> = []
|
||||
private var displayedVideoID: UUID?
|
||||
private var durationText: String?
|
||||
private var pendingRevealSessionID: UUID?
|
||||
private var revealedSessionID: UUID?
|
||||
private var isRevealScheduled = false
|
||||
private var previousIdleTimerDisabled: Bool?
|
||||
private var previousGestureEnabled: Bool?
|
||||
private let scrollView = UIScrollView()
|
||||
private let content = UIStackView()
|
||||
private let customerLabel = DroneDockStyle.label(size: 13, color: DroneDockStyle.secondary)
|
||||
private let fileLabel = DroneDockStyle.label("尚未选择视频", size: 16, weight: .semibold)
|
||||
private let fileDetailLabel = DroneDockStyle.label("选择一段已在本机的视频", size: 12, color: DroneDockStyle.secondary)
|
||||
private let chooseButton = UIButton(type: .system)
|
||||
private let previewButton = UIButton(type: .system)
|
||||
private let statusLabel = DroneDockStyle.label("准备闪传", size: 18, weight: .semibold)
|
||||
private let statusDetailLabel = DroneDockStyle.label(size: 13, color: DroneDockStyle.secondary)
|
||||
private let qrContainer = UIView()
|
||||
private let qrView = UIImageView()
|
||||
private let addressButton = UIButton(type: .system)
|
||||
private let expiryLabel = DroneDockStyle.label(size: 11, color: DroneDockStyle.secondary)
|
||||
private let progressView = UIProgressView(progressViewStyle: .default)
|
||||
private let progressLabel = DroneDockStyle.label(size: 12, color: DroneDockStyle.secondary)
|
||||
private let footer = UIView()
|
||||
private let primaryButton = UIButton(type: .system)
|
||||
private let footerLabel = DroneDockStyle.label("无需互联网 · 请双方保持连接同一 Wi-Fi", size: 11, color: DroneDockStyle.secondary)
|
||||
|
||||
/// 注入本地服务和测试视频选择器;默认使用禁止云端取片的本地相册选择器。
|
||||
init(customerTitle: String, viewModel: DroneDockNearbyTransferViewModel = DroneDockNearbyTransferViewModel(),
|
||||
videoPicker: (@MainActor () async throws -> DroneDockDeliveryVideo?)? = nil) {
|
||||
self.customerTitle = customerTitle
|
||||
self.viewModel = viewModel
|
||||
self.videoPicker = videoPicker
|
||||
super.init(nibName: nil, bundle: nil)
|
||||
hidesBottomBarWhenPushed = true
|
||||
}
|
||||
|
||||
@available(*, unavailable)
|
||||
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
|
||||
|
||||
deinit {
|
||||
operationTask?.cancel()
|
||||
metadataTask?.cancel()
|
||||
viewModel.setUpdateHandler(nil)
|
||||
viewModel.stop()
|
||||
ownedVideoURLs.forEach(DroneDockDeliveryVideoLoader.discard)
|
||||
NotificationCenter.default.removeObserver(self)
|
||||
}
|
||||
|
||||
override func setupNavigationBar() {
|
||||
title = "面对面闪传"
|
||||
let back = UIBarButtonItem(title: "交付方式", style: .plain, target: self, action: #selector(backTapped))
|
||||
back.accessibilityIdentifier = "drone.nearby.back"
|
||||
navigationItem.leftBarButtonItem = back
|
||||
let close = UIBarButtonItem(image: UIImage(systemName: "xmark"), style: .plain, target: self, action: #selector(closeTapped))
|
||||
close.accessibilityLabel = "关闭面对面闪传"
|
||||
close.accessibilityIdentifier = "drone.nearby.close"
|
||||
navigationItem.rightBarButtonItem = close
|
||||
}
|
||||
|
||||
override func setupUI() {
|
||||
view.backgroundColor = DroneDockStyle.background
|
||||
scrollView.alwaysBounceVertical = true
|
||||
scrollView.accessibilityIdentifier = "drone.nearby.content"
|
||||
content.axis = .vertical
|
||||
content.spacing = 14
|
||||
customerLabel.text = customerTitle
|
||||
customerLabel.numberOfLines = 0
|
||||
content.addArrangedSubview(customerLabel)
|
||||
let networkTitle = DroneDockStyle.label("1 连接同一 Wi-Fi", size: 15, weight: .semibold)
|
||||
let networkDetail = DroneDockStyle.label("请商家和游客连接同一 Wi-Fi。没有现场 Wi-Fi 时,可手动连接同一手机热点。", size: 13, color: DroneDockStyle.secondary)
|
||||
networkDetail.numberOfLines = 0
|
||||
content.addArrangedSubview(card([networkTitle, networkDetail]))
|
||||
let videoTitle = DroneDockStyle.label("2 选择本地视频", size: 15, weight: .semibold)
|
||||
fileLabel.numberOfLines = 2
|
||||
fileLabel.accessibilityIdentifier = "drone.nearby.fileName"
|
||||
fileDetailLabel.numberOfLines = 0
|
||||
fileDetailLabel.accessibilityIdentifier = "drone.nearby.fileDetail"
|
||||
chooseButton.setTitle("选择视频", for: .normal)
|
||||
chooseButton.titleLabel?.font = .systemFont(ofSize: 14, weight: .semibold)
|
||||
chooseButton.accessibilityIdentifier = "drone.nearby.chooseVideo"
|
||||
previewButton.setTitle("预览", for: .normal)
|
||||
previewButton.setImage(UIImage(systemName: "play.circle"), for: .normal)
|
||||
previewButton.accessibilityIdentifier = "drone.nearby.preview"
|
||||
let videoActions = UIStackView(arrangedSubviews: [chooseButton, previewButton])
|
||||
videoActions.spacing = 18
|
||||
videoActions.distribution = .fillEqually
|
||||
videoActions.snp.makeConstraints { $0.height.equalTo(44) }
|
||||
content.addArrangedSubview(card([videoTitle, fileLabel, fileDetailLabel, videoActions]))
|
||||
let sessionTitle = DroneDockStyle.label("3 游客扫码接收", size: 15, weight: .semibold)
|
||||
statusLabel.textColor = DroneDockStyle.primary
|
||||
statusLabel.accessibilityIdentifier = "drone.nearby.status"
|
||||
statusDetailLabel.numberOfLines = 0
|
||||
statusDetailLabel.accessibilityIdentifier = "drone.nearby.statusDetail"
|
||||
qrView.contentMode = .scaleAspectFit
|
||||
qrView.accessibilityIdentifier = "drone.nearby.qr"
|
||||
qrView.isAccessibilityElement = true
|
||||
qrView.accessibilityLabel = "请游客用系统相机扫描此二维码"
|
||||
qrContainer.addSubview(qrView)
|
||||
qrContainer.snp.makeConstraints { $0.height.equalTo(212) }
|
||||
qrView.snp.makeConstraints { make in make.center.equalToSuperview(); make.size.equalTo(204) }
|
||||
addressButton.titleLabel?.font = .monospacedSystemFont(ofSize: 11, weight: .regular)
|
||||
addressButton.titleLabel?.numberOfLines = 2
|
||||
addressButton.accessibilityIdentifier = "drone.nearby.copyAddress"
|
||||
addressButton.setTitle("复制接收地址", for: .normal)
|
||||
addressButton.snp.makeConstraints { $0.height.greaterThanOrEqualTo(44) }
|
||||
expiryLabel.textAlignment = .center
|
||||
expiryLabel.numberOfLines = 0
|
||||
expiryLabel.accessibilityIdentifier = "drone.nearby.expiry"
|
||||
progressView.progressTintColor = DroneDockStyle.primary
|
||||
progressView.accessibilityIdentifier = "drone.nearby.progress"
|
||||
progressLabel.textAlignment = .center
|
||||
progressLabel.accessibilityIdentifier = "drone.nearby.progressText"
|
||||
content.addArrangedSubview(card([sessionTitle, statusLabel, statusDetailLabel, qrContainer, addressButton, expiryLabel, progressView, progressLabel]))
|
||||
footer.backgroundColor = .white
|
||||
primaryButton.layer.cornerRadius = 12
|
||||
primaryButton.titleLabel?.font = .systemFont(ofSize: 16, weight: .semibold)
|
||||
primaryButton.setTitleColor(.white, for: .normal)
|
||||
primaryButton.setTitleColor(DroneDockStyle.secondary, for: .disabled)
|
||||
primaryButton.accessibilityIdentifier = "drone.nearby.primary"
|
||||
footerLabel.textAlignment = .center
|
||||
footerLabel.numberOfLines = 0
|
||||
view.addSubview(scrollView)
|
||||
scrollView.addSubview(content)
|
||||
view.addSubview(footer)
|
||||
[primaryButton, footerLabel].forEach(footer.addSubview)
|
||||
render()
|
||||
}
|
||||
|
||||
override func setupConstraints() {
|
||||
scrollView.snp.makeConstraints { make in
|
||||
make.top.equalTo(view.safeAreaLayoutGuide)
|
||||
make.leading.trailing.equalToSuperview()
|
||||
make.bottom.equalTo(footer.snp.top)
|
||||
}
|
||||
content.snp.makeConstraints { make in
|
||||
make.edges.equalTo(scrollView.contentLayoutGuide).inset(16)
|
||||
make.width.equalTo(scrollView.frameLayoutGuide).offset(-32)
|
||||
}
|
||||
footer.snp.makeConstraints { $0.leading.trailing.bottom.equalToSuperview() }
|
||||
primaryButton.snp.makeConstraints { make in
|
||||
make.top.equalToSuperview().offset(12)
|
||||
make.leading.trailing.equalToSuperview().inset(16)
|
||||
make.height.equalTo(48)
|
||||
}
|
||||
footerLabel.snp.makeConstraints { make in
|
||||
make.top.equalTo(primaryButton.snp.bottom).offset(9)
|
||||
make.leading.trailing.equalTo(primaryButton)
|
||||
make.bottom.equalTo(footer.safeAreaLayoutGuide).offset(-10)
|
||||
}
|
||||
}
|
||||
|
||||
override func bindActions() {
|
||||
chooseButton.addTarget(self, action: #selector(chooseVideoTapped), for: .touchUpInside)
|
||||
previewButton.addTarget(self, action: #selector(previewTapped), for: .touchUpInside)
|
||||
primaryButton.addTarget(self, action: #selector(primaryTapped), for: .touchUpInside)
|
||||
addressButton.addTarget(self, action: #selector(copyAddressTapped), for: .touchUpInside)
|
||||
viewModel.setUpdateHandler { [weak self] _ in
|
||||
Task { @MainActor [weak self] in self?.render() }
|
||||
}
|
||||
NotificationCenter.default.addObserver(self, selector: #selector(enteredBackground), name: UIApplication.didEnterBackgroundNotification, object: nil)
|
||||
}
|
||||
|
||||
override func viewWillAppear(_ animated: Bool) {
|
||||
super.viewWillAppear(animated)
|
||||
navigationController?.setNavigationBarHidden(false, animated: false)
|
||||
navigationController?.sheetPresentationController?.detents = [.large()]
|
||||
navigationController?.sheetPresentationController?.selectedDetentIdentifier = .large
|
||||
render()
|
||||
}
|
||||
|
||||
override func viewWillDisappear(_ animated: Bool) {
|
||||
super.viewWillDisappear(animated)
|
||||
if isMovingFromParent || isBeingDismissed || navigationController?.isBeingDismissed == true {
|
||||
finishForLeaving()
|
||||
}
|
||||
}
|
||||
|
||||
override func viewDidLayoutSubviews() {
|
||||
super.viewDidLayoutSubviews()
|
||||
scheduleReceiveCodeReveal()
|
||||
}
|
||||
|
||||
private func scheduleReceiveCodeReveal() {
|
||||
guard pendingRevealSessionID != nil, !isRevealScheduled else { return }
|
||||
isRevealScheduled = true
|
||||
DispatchQueue.main.async { [weak self] in
|
||||
guard let self else { return }
|
||||
defer { self.isRevealScheduled = false }
|
||||
self.view.layoutIfNeeded()
|
||||
self.scrollView.layoutIfNeeded()
|
||||
self.content.layoutIfNeeded()
|
||||
self.revealReceiveCodeIfNeeded()
|
||||
}
|
||||
}
|
||||
|
||||
private func revealReceiveCodeIfNeeded() {
|
||||
guard let sessionID = pendingRevealSessionID,
|
||||
viewModel.snapshot.session?.id == sessionID,
|
||||
view.window != nil, scrollView.bounds.height > 0,
|
||||
qrContainer.bounds.height > 0, expiryLabel.bounds.height > 0 else { return }
|
||||
pendingRevealSessionID = nil
|
||||
revealedSessionID = sessionID
|
||||
// 只在新接收码生成后定位一次;下载进度和游客连接事件不抢走用户的滚动位置。
|
||||
let target = qrContainer.convert(qrContainer.bounds, to: scrollView)
|
||||
.union(addressButton.convert(addressButton.bounds, to: scrollView))
|
||||
.union(expiryLabel.convert(expiryLabel.bounds, to: scrollView))
|
||||
.insetBy(dx: 0, dy: -8)
|
||||
scrollView.scrollRectToVisible(target, animated: !UIAccessibility.isReduceMotionEnabled)
|
||||
}
|
||||
|
||||
private func card(_ views: [UIView]) -> UIView {
|
||||
let container = UIView()
|
||||
DroneDockStyle.applyCard(to: container)
|
||||
let stack = UIStackView(arrangedSubviews: views)
|
||||
stack.axis = .vertical
|
||||
stack.spacing = 10
|
||||
container.addSubview(stack)
|
||||
stack.snp.makeConstraints { $0.edges.equalToSuperview().inset(16) }
|
||||
return container
|
||||
}
|
||||
|
||||
private func render() {
|
||||
guard isViewLoaded else { return }
|
||||
let state = viewModel.snapshot
|
||||
updateScreenAwake(active: state.isActive)
|
||||
navigationController?.isModalInPresentation = state.isActive || isPicking
|
||||
if state.isActive {
|
||||
if previousGestureEnabled == nil { previousGestureEnabled = navigationController?.interactivePopGestureRecognizer?.isEnabled }
|
||||
navigationController?.interactivePopGestureRecognizer?.isEnabled = false
|
||||
} else if let enabled = previousGestureEnabled {
|
||||
navigationController?.interactivePopGestureRecognizer?.isEnabled = enabled
|
||||
previousGestureEnabled = nil
|
||||
}
|
||||
chooseButton.isEnabled = state.canChooseVideo && !isPicking
|
||||
chooseButton.setTitle(isPicking ? "正在准备视频…" : state.video == nil ? "选择视频" : "重新选择", for: .normal)
|
||||
previewButton.isHidden = state.video == nil
|
||||
previewButton.isEnabled = !isPicking && !state.isActive
|
||||
fileLabel.text = state.video?.fileName ?? "尚未选择视频"
|
||||
if let video = state.video {
|
||||
let size = ByteCountFormatter.string(fromByteCount: Int64(video.fileSize), countStyle: .file)
|
||||
fileDetailLabel.text = [size, durationText].compactMap { $0 }.joined(separator: " · ")
|
||||
} else { fileDetailLabel.text = "选择一段已在本机的视频,仅本次闪传可访问" }
|
||||
if let pickerError { statusLabel.text = "视频准备失败"; statusDetailLabel.text = pickerError }
|
||||
else {
|
||||
switch state.phase {
|
||||
case .idle:
|
||||
statusLabel.text = "准备闪传"
|
||||
statusDetailLabel.text = "选择视频后生成二维码,游客使用系统相机扫码,在浏览器中接收。"
|
||||
case .starting:
|
||||
statusLabel.text = "正在准备接收码…"
|
||||
statusDetailLabel.text = "请保持本页打开,正在检查本地连接。"
|
||||
case .waiting:
|
||||
statusLabel.text = "等待游客扫码"
|
||||
statusDetailLabel.text = "请游客先连接同一 Wi-Fi,再用系统相机扫码。传输期间请保持本页亮屏。"
|
||||
case .connected:
|
||||
statusLabel.text = "游客已打开接收页"
|
||||
statusDetailLabel.text = state.message ?? "请游客点击“下载视频”开始接收。"
|
||||
case .sending:
|
||||
statusLabel.text = "正在发送视频"
|
||||
statusDetailLabel.text = "请保持本页亮屏,并让游客保持连接同一 Wi-Fi。"
|
||||
case .sent:
|
||||
statusLabel.text = "文件已发送"
|
||||
statusDetailLabel.text = state.message
|
||||
case .interrupted:
|
||||
statusLabel.text = "传输已中断"
|
||||
statusDetailLabel.text = state.message
|
||||
case .ended:
|
||||
statusLabel.text = "闪传已结束"
|
||||
statusDetailLabel.text = state.message
|
||||
case .failed:
|
||||
statusLabel.text = "暂时无法闪传"
|
||||
statusDetailLabel.text = state.message
|
||||
}
|
||||
}
|
||||
statusLabel.textColor = state.phase == .sent ? DroneDockStyle.success : state.phase == .failed || state.phase == .interrupted || pickerError != nil ? DroneDockStyle.warning : DroneDockStyle.primary
|
||||
let receiveURL = state.session?.url
|
||||
qrContainer.isHidden = receiveURL == nil
|
||||
addressButton.isHidden = receiveURL == nil
|
||||
expiryLabel.isHidden = receiveURL == nil
|
||||
if let receiveURL {
|
||||
if qrView.accessibilityValue != receiveURL.absoluteString {
|
||||
qrView.image = QRCodeGenerator.generateStyledQRCode(content: receiveURL.absoluteString, backgroundColor: .white, cornerRadius: 0)
|
||||
qrView.accessibilityValue = receiveURL.absoluteString
|
||||
}
|
||||
addressButton.accessibilityValue = receiveURL.absoluteString
|
||||
if let expiry = state.session?.expiresAt {
|
||||
expiryLabel.text = "接收码有效至 \(expiry.formatted(date: .omitted, time: .shortened))\n结束闪传或离开本页后失效"
|
||||
}
|
||||
} else {
|
||||
qrView.image = nil
|
||||
qrView.accessibilityValue = nil
|
||||
addressButton.accessibilityValue = nil
|
||||
}
|
||||
let hasProgress = [.sending, .sent, .interrupted].contains(state.phase)
|
||||
progressView.isHidden = !hasProgress
|
||||
progressLabel.isHidden = !hasProgress
|
||||
progressView.setProgress(state.progress, animated: state.phase == .sending)
|
||||
progressLabel.text = "已发送 \(ByteCountFormatter.string(fromByteCount: state.bytesSent, countStyle: .file)) / \(ByteCountFormatter.string(fromByteCount: state.totalBytes, countStyle: .file))"
|
||||
primaryButton.setTitle(state.isActive ? "结束闪传" : state.phase == .ended || state.phase == .failed ? "重新生成接收码" : "生成接收二维码", for: .normal)
|
||||
primaryButton.isEnabled = !isPicking && (state.isActive || state.canStart)
|
||||
primaryButton.backgroundColor = primaryButton.isEnabled ? DroneDockStyle.primary : DroneDockStyle.border
|
||||
if let sessionID = state.session?.id, sessionID != revealedSessionID {
|
||||
pendingRevealSessionID = sessionID
|
||||
} else if state.session == nil { pendingRevealSessionID = nil }
|
||||
view.setNeedsLayout()
|
||||
scheduleReceiveCodeReveal()
|
||||
}
|
||||
|
||||
@objc private func chooseVideoTapped() {
|
||||
guard viewModel.snapshot.canChooseVideo, !isPicking else { return }
|
||||
pickerError = nil
|
||||
if let videoPicker {
|
||||
isPicking = true
|
||||
render()
|
||||
operationTask = Task { @MainActor [weak self] in
|
||||
guard let self else { return }
|
||||
defer { self.isPicking = false; self.render() }
|
||||
do {
|
||||
if let video = try await videoPicker() {
|
||||
guard !Task.isCancelled else { DroneDockDeliveryVideoLoader.discard(video.url); return }
|
||||
self.useVideo(video)
|
||||
}
|
||||
} catch { if !Task.isCancelled { self.pickerError = error.localizedDescription } }
|
||||
}
|
||||
} else {
|
||||
let picker = DroneDockNearbyVideoPickerViewController(onSelect: { [weak self] video in
|
||||
guard let self else { DroneDockDeliveryVideoLoader.discard(video.url); return }
|
||||
self.dismiss(animated: true)
|
||||
self.useVideo(video)
|
||||
}, onCancel: { [weak self] in self?.dismiss(animated: true) })
|
||||
present(UINavigationController(rootViewController: picker), animated: true)
|
||||
}
|
||||
}
|
||||
|
||||
private func useVideo(_ video: DroneDockDeliveryVideo) {
|
||||
do {
|
||||
guard try viewModel.selectVideo(video) else { DroneDockDeliveryVideoLoader.discard(video.url); return }
|
||||
ownedVideoURLs.insert(video.url)
|
||||
let obsolete = ownedVideoURLs.filter { $0 != video.url }
|
||||
obsolete.forEach(DroneDockDeliveryVideoLoader.discard)
|
||||
ownedVideoURLs.subtract(obsolete)
|
||||
pickerError = nil
|
||||
durationText = nil
|
||||
displayedVideoID = video.id
|
||||
metadataTask?.cancel()
|
||||
metadataTask = Task { @MainActor [weak self] in
|
||||
let duration = try? await AVURLAsset(url: video.url).load(.duration)
|
||||
guard !Task.isCancelled, let self, self.displayedVideoID == video.id else { return }
|
||||
if let seconds = duration?.seconds, seconds.isFinite, seconds > 0 {
|
||||
let whole = Int(seconds.rounded())
|
||||
self.durationText = String(format: "%d:%02d", whole / 60, whole % 60)
|
||||
}
|
||||
self.render()
|
||||
}
|
||||
} catch { DroneDockDeliveryVideoLoader.discard(video.url); pickerError = error.localizedDescription }
|
||||
render()
|
||||
}
|
||||
|
||||
@objc private func primaryTapped() {
|
||||
guard !isPicking else { return }
|
||||
if viewModel.snapshot.isActive {
|
||||
confirmStop { [weak self] in
|
||||
self?.operationTask?.cancel()
|
||||
self?.viewModel.stop()
|
||||
self?.render()
|
||||
}
|
||||
} else if viewModel.snapshot.canStart {
|
||||
pickerError = nil
|
||||
operationTask = Task { [weak self] in
|
||||
guard let self else { return }
|
||||
await self.viewModel.start()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@objc private func previewTapped() {
|
||||
guard let video = viewModel.snapshot.video, !viewModel.snapshot.isActive else { return }
|
||||
let player = AVPlayerViewController()
|
||||
player.player = AVPlayer(url: video.url)
|
||||
present(player, animated: true) { player.player?.play() }
|
||||
}
|
||||
|
||||
@objc private func copyAddressTapped() {
|
||||
guard let url = viewModel.snapshot.session?.url else { return }
|
||||
UIPasteboard.general.setItems([[UIPasteboard.typeAutomatic: url.absoluteString]], options: [.localOnly: true, .expirationDate: Date().addingTimeInterval(120)])
|
||||
let alert = UIAlertController(title: "接收地址已复制", message: "请仅分享给同一 Wi-Fi 下的游客。", preferredStyle: .alert)
|
||||
alert.addAction(UIAlertAction(title: "知道了", style: .default))
|
||||
present(alert, animated: true)
|
||||
}
|
||||
|
||||
@objc private func backTapped() {
|
||||
requestExit { [weak self] in self?.navigationController?.popViewController(animated: true) }
|
||||
}
|
||||
|
||||
@objc private func closeTapped() {
|
||||
requestExit { [weak self] in
|
||||
guard let self else { return }
|
||||
if let onClose = self.onClose { onClose() }
|
||||
else { self.dismiss(animated: true) }
|
||||
}
|
||||
}
|
||||
|
||||
private func requestExit(_ exit: @escaping () -> Void) {
|
||||
guard presentedViewController == nil else { return }
|
||||
let finish = { [weak self] in self?.finishForLeaving(); exit() }
|
||||
if viewModel.snapshot.isActive { confirmStop(finish) }
|
||||
else { finish() }
|
||||
}
|
||||
|
||||
private func confirmStop(_ completion: @escaping () -> Void) {
|
||||
let alert = UIAlertController(title: "结束本次闪传?", message: "正在下载的视频会停止,原接收二维码将失效。", preferredStyle: .alert)
|
||||
alert.addAction(UIAlertAction(title: "继续闪传", style: .cancel))
|
||||
alert.addAction(UIAlertAction(title: "结束闪传", style: .destructive) { _ in completion() })
|
||||
present(alert, animated: true)
|
||||
}
|
||||
|
||||
@objc private func enteredBackground() {
|
||||
guard viewModel.snapshot.isActive else { return }
|
||||
operationTask?.cancel()
|
||||
viewModel.stop(message: "App 已离开前台,本次闪传已结束。请重新生成二维码。")
|
||||
render()
|
||||
}
|
||||
|
||||
private func finishForLeaving() {
|
||||
operationTask?.cancel()
|
||||
metadataTask?.cancel()
|
||||
viewModel.stop()
|
||||
updateScreenAwake(active: false)
|
||||
navigationController?.isModalInPresentation = false
|
||||
if let enabled = previousGestureEnabled {
|
||||
navigationController?.interactivePopGestureRecognizer?.isEnabled = enabled
|
||||
previousGestureEnabled = nil
|
||||
}
|
||||
}
|
||||
|
||||
private func updateScreenAwake(active: Bool) {
|
||||
if active {
|
||||
if previousIdleTimerDisabled == nil { previousIdleTimerDisabled = UIApplication.shared.isIdleTimerDisabled }
|
||||
UIApplication.shared.isIdleTimerDisabled = true
|
||||
} else if let previous = previousIdleTimerDisabled {
|
||||
UIApplication.shared.isIdleTimerDisabled = previous
|
||||
previousIdleTimerDisabled = nil
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,322 @@
|
||||
import AVFoundation
|
||||
import Photos
|
||||
import PhotosUI
|
||||
import SnapKit
|
||||
import UIKit
|
||||
|
||||
/// 闪传专用本地视频选择器;缩略图与视频资源均禁止从 iCloud 下载。
|
||||
@MainActor
|
||||
final class DroneDockNearbyVideoPickerViewController: BaseViewController {
|
||||
private let onSelect: (DroneDockDeliveryVideo) -> Void
|
||||
private let onCancel: () -> Void
|
||||
private let manager = PHCachingImageManager()
|
||||
private var assets: [String: PHAsset] = [:]
|
||||
private var operation: Task<Void, Never>?
|
||||
private var hasFinished = false
|
||||
private var lastAuthorizationStatus: PHAuthorizationStatus?
|
||||
private var isObservingLibrary = false
|
||||
private var needsLibraryRefresh = false
|
||||
private let messageLabel = UILabel()
|
||||
private let spinner = UIActivityIndicatorView(style: .medium)
|
||||
private let accessButton = UIButton(type: .system)
|
||||
private lazy var collection = UICollectionView(frame: .zero, collectionViewLayout: makeLayout())
|
||||
private var dataSource: UICollectionViewDiffableDataSource<Int, String>!
|
||||
|
||||
/// 只返回已经复制到 App 独占临时目录的视频,由调用页负责清理。
|
||||
init(onSelect: @escaping (DroneDockDeliveryVideo) -> Void, onCancel: @escaping () -> Void) {
|
||||
self.onSelect = onSelect
|
||||
self.onCancel = onCancel
|
||||
super.init(nibName: nil, bundle: nil)
|
||||
}
|
||||
|
||||
@available(*, unavailable)
|
||||
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
|
||||
|
||||
deinit {
|
||||
PHPhotoLibrary.shared().unregisterChangeObserver(self)
|
||||
NotificationCenter.default.removeObserver(self)
|
||||
}
|
||||
|
||||
override func setupNavigationBar() {
|
||||
title = "选择本地视频"
|
||||
navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: .plain, target: self, action: #selector(cancel))
|
||||
}
|
||||
|
||||
override func setupUI() {
|
||||
view.backgroundColor = .systemBackground
|
||||
messageLabel.font = .systemFont(ofSize: 13)
|
||||
messageLabel.textColor = .secondaryLabel
|
||||
messageLabel.numberOfLines = 0
|
||||
messageLabel.text = "仅发送本机已有视频,不下载 iCloud 视频。首次使用请允许访问需要交付的视频。"
|
||||
collection.backgroundColor = .systemBackground
|
||||
collection.accessibilityIdentifier = "drone.nearby.picker.list"
|
||||
collection.delegate = self
|
||||
collection.register(NearbyVideoCell.self, forCellWithReuseIdentifier: "video")
|
||||
accessButton.setTitle("选择更多可访问的视频", for: .normal)
|
||||
accessButton.addTarget(self, action: #selector(manageAccess), for: .touchUpInside)
|
||||
accessButton.isHidden = true
|
||||
[messageLabel, accessButton, collection, spinner].forEach(view.addSubview)
|
||||
dataSource = UICollectionViewDiffableDataSource<Int, String>(collectionView: collection) { [weak self] list, path, id in
|
||||
let cell = list.dequeueReusableCell(withReuseIdentifier: "video", for: path) as! NearbyVideoCell
|
||||
if let self, let asset = self.assets[id] { cell.apply(asset: asset, manager: self.manager) }
|
||||
return cell
|
||||
}
|
||||
PHPhotoLibrary.shared().register(self)
|
||||
isObservingLibrary = true
|
||||
operation = Task { @MainActor [weak self] in
|
||||
let status = await PHPhotoLibrary.requestAuthorization(for: .readWrite)
|
||||
guard !Task.isCancelled, let self else { return }
|
||||
self.loadAssets(status: status)
|
||||
self.operation = nil
|
||||
self.applyPendingLibraryRefresh()
|
||||
}
|
||||
}
|
||||
|
||||
override func setupConstraints() {
|
||||
messageLabel.snp.makeConstraints { make in
|
||||
make.top.equalTo(view.safeAreaLayoutGuide).offset(16)
|
||||
make.leading.trailing.equalToSuperview().inset(20)
|
||||
}
|
||||
accessButton.snp.makeConstraints { make in
|
||||
make.top.equalTo(messageLabel.snp.bottom).offset(8)
|
||||
make.leading.trailing.equalToSuperview().inset(20)
|
||||
make.height.equalTo(36)
|
||||
}
|
||||
collection.snp.makeConstraints { make in
|
||||
make.top.equalTo(accessButton.snp.bottom).offset(8)
|
||||
make.leading.trailing.bottom.equalTo(view.safeAreaLayoutGuide)
|
||||
}
|
||||
spinner.snp.makeConstraints { make in make.center.equalToSuperview() }
|
||||
}
|
||||
|
||||
override func bindActions() {
|
||||
NotificationCenter.default.addObserver(self, selector: #selector(refreshAuthorization),
|
||||
name: UIApplication.didBecomeActiveNotification, object: nil)
|
||||
}
|
||||
|
||||
override func viewWillAppear(_ animated: Bool) {
|
||||
super.viewWillAppear(animated)
|
||||
refreshAuthorization()
|
||||
}
|
||||
|
||||
override func viewDidDisappear(_ animated: Bool) {
|
||||
super.viewDidDisappear(animated)
|
||||
if isBeingDismissed || navigationController?.isBeingDismissed == true {
|
||||
operation?.cancel()
|
||||
stopObservingLibrary()
|
||||
if !hasFinished { hasFinished = true; onCancel() }
|
||||
}
|
||||
}
|
||||
|
||||
private func makeLayout() -> UICollectionViewLayout {
|
||||
UICollectionViewCompositionalLayout { _, environment in
|
||||
let side = (environment.container.effectiveContentSize.width - 32) / 3
|
||||
let item = NSCollectionLayoutItem(layoutSize: .init(widthDimension: .fractionalWidth(1.0 / 3), heightDimension: .fractionalHeight(1)))
|
||||
item.contentInsets = .init(top: 2, leading: 2, bottom: 2, trailing: 2)
|
||||
let group = NSCollectionLayoutGroup.horizontal(layoutSize: .init(widthDimension: .fractionalWidth(1), heightDimension: .absolute(side)), subitems: [item])
|
||||
let section = NSCollectionLayoutSection(group: group)
|
||||
section.contentInsets = .init(top: 0, leading: 14, bottom: 20, trailing: 14)
|
||||
return section
|
||||
}
|
||||
}
|
||||
|
||||
private func loadAssets(status: PHAuthorizationStatus) {
|
||||
lastAuthorizationStatus = status
|
||||
guard status == .authorized || status == .limited else {
|
||||
assets.removeAll()
|
||||
var snapshot = NSDiffableDataSourceSnapshot<Int, String>()
|
||||
snapshot.appendSections([0])
|
||||
dataSource.apply(snapshot, animatingDifferences: true)
|
||||
messageLabel.text = "请在系统设置中允许访问相册,再选择手机中的视频。"
|
||||
accessButton.isHidden = false
|
||||
accessButton.setTitle("打开相册权限设置", for: .normal)
|
||||
return
|
||||
}
|
||||
accessButton.isHidden = status != .limited
|
||||
accessButton.setTitle("选择更多可访问的视频", for: .normal)
|
||||
let options = PHFetchOptions()
|
||||
options.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]
|
||||
let result = PHAsset.fetchAssets(with: .video, options: options)
|
||||
assets.removeAll()
|
||||
var ids: [String] = []
|
||||
result.enumerateObjects { asset, _, _ in
|
||||
self.assets[asset.localIdentifier] = asset
|
||||
ids.append(asset.localIdentifier)
|
||||
}
|
||||
var snapshot = NSDiffableDataSourceSnapshot<Int, String>()
|
||||
snapshot.appendSections([0]); snapshot.appendItems(ids)
|
||||
dataSource.apply(snapshot, animatingDifferences: true)
|
||||
messageLabel.text = ids.isEmpty ? "暂无可访问的视频。请先将成片保存在本机相册,或允许访问更多视频。" : "选择一段本地成片。仅存于 iCloud 的视频不会下载;单个视频不超过 2 GB。"
|
||||
}
|
||||
|
||||
@objc private func refreshAuthorization() {
|
||||
guard !hasFinished, isViewLoaded else { return }
|
||||
let status = PHPhotoLibrary.authorizationStatus(for: .readWrite)
|
||||
guard status != .notDetermined, status != lastAuthorizationStatus || status == .limited else { return }
|
||||
requestLibraryRefresh()
|
||||
}
|
||||
|
||||
private func requestLibraryRefresh() {
|
||||
guard !hasFinished, isViewLoaded else { return }
|
||||
needsLibraryRefresh = true
|
||||
applyPendingLibraryRefresh()
|
||||
}
|
||||
|
||||
private func applyPendingLibraryRefresh() {
|
||||
guard needsLibraryRefresh, !hasFinished, operation == nil else { return }
|
||||
needsLibraryRefresh = false
|
||||
loadAssets(status: PHPhotoLibrary.authorizationStatus(for: .readWrite))
|
||||
}
|
||||
|
||||
private func stopObservingLibrary() {
|
||||
guard isObservingLibrary else { return }
|
||||
isObservingLibrary = false
|
||||
needsLibraryRefresh = false
|
||||
PHPhotoLibrary.shared().unregisterChangeObserver(self)
|
||||
}
|
||||
|
||||
@objc private func manageAccess() {
|
||||
if PHPhotoLibrary.authorizationStatus(for: .readWrite) == .limited {
|
||||
PHPhotoLibrary.shared().presentLimitedLibraryPicker(from: self) { [weak self] _ in
|
||||
// 完成回调可能早于 Photos 可访问资产集合更新;后续库变化通知会再次刷新。
|
||||
Task { @MainActor [weak self] in self?.requestLibraryRefresh() }
|
||||
}
|
||||
} else if let url = URL(string: UIApplication.openSettingsURLString) { UIApplication.shared.open(url) }
|
||||
}
|
||||
|
||||
@objc private func cancel() {
|
||||
operation?.cancel()
|
||||
guard !hasFinished else { return }
|
||||
hasFinished = true
|
||||
stopObservingLibrary()
|
||||
onCancel()
|
||||
}
|
||||
}
|
||||
|
||||
extension DroneDockNearbyVideoPickerViewController: UICollectionViewDelegate {
|
||||
/// 选择后仅请求本地资源;资源在云端时保留选择界面并显示原因。
|
||||
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
|
||||
guard operation == nil, let id = dataSource.itemIdentifier(for: indexPath), let asset = assets[id] else { return }
|
||||
spinner.startAnimating()
|
||||
collection.isUserInteractionEnabled = false
|
||||
messageLabel.text = "正在准备本地视频…"
|
||||
operation = Task { @MainActor [weak self] in
|
||||
guard let self else { return }
|
||||
var failureMessage: String?
|
||||
defer {
|
||||
self.operation = nil
|
||||
self.spinner.stopAnimating()
|
||||
self.collection.isUserInteractionEnabled = true
|
||||
self.applyPendingLibraryRefresh()
|
||||
if let failureMessage, !self.hasFinished { self.messageLabel.text = failureMessage }
|
||||
}
|
||||
do {
|
||||
let video = try await DroneDockNearbyVideoLoader.load(asset: asset)
|
||||
guard !Task.isCancelled, !self.hasFinished else { DroneDockDeliveryVideoLoader.discard(video.url); return }
|
||||
self.hasFinished = true
|
||||
self.stopObservingLibrary()
|
||||
self.onSelect(video)
|
||||
} catch {
|
||||
if !Task.isCancelled { failureMessage = error.localizedDescription }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension DroneDockNearbyVideoPickerViewController: PHPhotoLibraryChangeObserver {
|
||||
/// Photos 回调线程不固定;只刷新本地资产元数据,导出过程中合并到结束后处理。
|
||||
nonisolated func photoLibraryDidChange(_ changeInstance: PHChange) {
|
||||
Task { @MainActor [weak self] in self?.requestLibraryRefresh() }
|
||||
}
|
||||
}
|
||||
|
||||
/// 视频网格单元,取消复用中的缩略图请求,禁止图片从云端加载。
|
||||
@MainActor
|
||||
private final class NearbyVideoCell: UICollectionViewCell {
|
||||
private let thumbnail = UIImageView()
|
||||
private let duration = UILabel()
|
||||
private var representedID: String?
|
||||
private var request: PHImageRequestID = PHInvalidImageRequestID
|
||||
private weak var manager: PHImageManager?
|
||||
|
||||
override init(frame: CGRect) {
|
||||
super.init(frame: frame)
|
||||
contentView.backgroundColor = .secondarySystemBackground
|
||||
contentView.layer.cornerRadius = 8
|
||||
contentView.clipsToBounds = true
|
||||
thumbnail.contentMode = .scaleAspectFill
|
||||
thumbnail.clipsToBounds = true
|
||||
duration.textColor = .white
|
||||
duration.font = .monospacedDigitSystemFont(ofSize: 12, weight: .medium)
|
||||
duration.backgroundColor = UIColor.black.withAlphaComponent(0.6)
|
||||
duration.textAlignment = .center
|
||||
contentView.addSubview(thumbnail); contentView.addSubview(duration)
|
||||
thumbnail.snp.makeConstraints { $0.edges.equalToSuperview() }
|
||||
duration.snp.makeConstraints { make in make.trailing.bottom.equalToSuperview().inset(4); make.width.greaterThanOrEqualTo(42); make.height.equalTo(20) }
|
||||
isAccessibilityElement = true
|
||||
}
|
||||
|
||||
@available(*, unavailable)
|
||||
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
|
||||
|
||||
override func prepareForReuse() {
|
||||
super.prepareForReuse()
|
||||
if request != PHInvalidImageRequestID { manager?.cancelImageRequest(request) }
|
||||
request = PHInvalidImageRequestID; representedID = nil; thumbnail.image = nil
|
||||
}
|
||||
|
||||
/// 只读取本地缩略图,异步回调核对资产身份,避免复用串图。
|
||||
func apply(asset: PHAsset, manager: PHImageManager) {
|
||||
prepareForReuse()
|
||||
self.manager = manager
|
||||
representedID = asset.localIdentifier
|
||||
let seconds = Int(asset.duration.rounded())
|
||||
duration.text = String(format: "%d:%02d", seconds / 60, seconds % 60)
|
||||
accessibilityLabel = "视频,\(duration.text ?? "")"
|
||||
thumbnail.image = UIImage(systemName: "video")
|
||||
let options = PHImageRequestOptions()
|
||||
options.isNetworkAccessAllowed = false
|
||||
options.deliveryMode = .opportunistic
|
||||
let id = asset.localIdentifier
|
||||
request = manager.requestImage(for: asset, targetSize: CGSize(width: 300, height: 300), contentMode: .aspectFill, options: options) { [weak self] image, _ in
|
||||
Task { @MainActor in
|
||||
guard let self, self.representedID == id, let image else { return }
|
||||
self.thumbnail.image = image
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 导出本机 Photos 资源,网络访问始终关闭,不借助系统文件提供器下载云端内容。
|
||||
enum DroneDockNearbyVideoLoader {
|
||||
/// 构造明确禁用云端下载的资源参数,供资源导出及回归测试共同使用。
|
||||
static func localResourceOptions() -> PHAssetResourceRequestOptions {
|
||||
DroneDockNearbyVideoResourceWriter.localResourceOptions()
|
||||
}
|
||||
|
||||
/// 导出当前视频资源后复用成片校验和独占文件生命周期。
|
||||
@MainActor
|
||||
static func load(asset: PHAsset) async throws -> DroneDockDeliveryVideo {
|
||||
let resources = PHAssetResource.assetResources(for: asset)
|
||||
guard let resource = resources.first(where: { $0.type == .fullSizeVideo }) ?? resources.first(where: { $0.type == .video }) else { throw LocalVideoError.unavailable }
|
||||
let directory = FileManager.default.temporaryDirectory.appendingPathComponent("nearby-video-import-\(UUID().uuidString)", isDirectory: true)
|
||||
try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
|
||||
defer { try? FileManager.default.removeItem(at: directory) }
|
||||
let name = URL(fileURLWithPath: resource.originalFilename).lastPathComponent
|
||||
let url = directory.appendingPathComponent(name)
|
||||
try Task.checkCancellation()
|
||||
do {
|
||||
try await DroneDockNearbyVideoResourceWriter.write(resource: resource, to: url)
|
||||
} catch is CancellationError { throw CancellationError() }
|
||||
catch let error as DroneDockFilmError { throw error }
|
||||
catch { throw LocalVideoError.unavailable }
|
||||
try Task.checkCancellation()
|
||||
return try await DroneDockDeliveryVideoLoader.load(documentURL: url)
|
||||
}
|
||||
|
||||
/// 本地不可读取时明确提示,不自动退回云端获取。
|
||||
private enum LocalVideoError: LocalizedError {
|
||||
case unavailable
|
||||
var errorDescription: String? { "无法读取本地视频,视频可能仅存于 iCloud。请选取已完整保存在本机的视频。" }
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,20 @@ import UIKit
|
||||
enum DroneDockPreview {
|
||||
/// 启动参数存在时返回预览导航,正常冷启动继续使用原业务根页面。
|
||||
static func navigationController(arguments: [String]) -> UINavigationController? {
|
||||
if arguments.contains("--dock-nearby-preview") {
|
||||
if arguments.contains("--dock-nearby-library") {
|
||||
return UINavigationController(rootViewController: DroneDockNearbyTransferViewController(
|
||||
customerTitle: "本地相册测试 · 非游客订单"))
|
||||
}
|
||||
let nearby = DroneDockNearbyTransferViewController(customerTitle: "本地测试视频 · 非游客订单", videoPicker: {
|
||||
guard let source = Bundle.main.url(forResource: "drone_material_demo", withExtension: "mp4")
|
||||
?? Bundle.main.url(forResource: "drone_material_demo", withExtension: "mp4", subdirectory: "DroneDock") else {
|
||||
throw DroneDockFilmError.invalidLocalFile
|
||||
}
|
||||
return try await DroneDockDeliveryVideoLoader.load(documentURL: source)
|
||||
})
|
||||
return UINavigationController(rootViewController: nearby)
|
||||
}
|
||||
if let materials = DroneDockMaterialsSimulation.makeController(arguments: arguments) {
|
||||
return UINavigationController(rootViewController: materials)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user