feat(drone-dock): 实现局域网扫码直传交付
This commit is contained in:
@@ -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。请选取已完整保存在本机的视频。" }
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user