feat(drone-dock): 实现局域网扫码直传交付
This commit is contained in:
@@ -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
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user