feat: 新增 iPhone 客户端,含隔空投送式点对点互传
三条链路: - 电脑 → iPhone:扫 QFTSEND2 码下载,流式落盘 + 增量 SHA-256, 支持 Range 断点续传 - iPhone → 电脑:扫 QFTPAIR2 码后 init/chunk/finish 并行分块上传 - iPhone ↔ iPhone:QFTP2P1 扫码握手,Network.framework 开启 includePeerToPeer(AirDrop 同款 BLE 发现 + AWDL 点对点 Wi-Fi), 两台设备不需要连同一个 Wi-Fi,也不需要路由器 P2P 用 TLS-PSK 握手:32 字节预共享密钥由发送端随机生成并写进二维码, 扫码这个动作本身完成带外密钥交换与双向认证,无需证书体系与配对弹窗。 未扫到码的第三方连上来过不了握手。 核心层刻意不 import UIKit,可直接以 macOS 为目标编译测试, 不需要 Xcode 也不需要模拟器,已接入主自检套件,72 项全部通过: - 端点白名单 11 种拒绝用例(域名、公网、172.32 边界、 非规范八位组、IPv6、带凭据/路径/query) - CoreTests/MockPCServer.py 严格复刻 receiver.rs / sender.rs 的线上语义 (路径、header 名、JSON 字段、Range 行为、chunk 长度校验), 构成 Swift 与 Rust 两端的线格式契约测试,任一端改协议即会失败 - 真实 TLS-PSK 握手下的 P2P 端到端传输,含错误密钥必须被拒 iOS 平台限制(已在 ios/README.md 说明): NEHotspotConfiguration 需要付费账号 entitlement,故不实现 Direct AP 流程,与电脑互传要求同一局域网;AWDL 是苹果私有链路,Windows 无法参与。 上传块固定 4 MiB 而非 Android 的 4/8/16 MiB,因为 iOS 上 worker 数 × 块大小即内存峰值。 未验证部分:本机只有 Command Line Tools,无 Xcode 与 iOS SDK, UI 层(SwiftUI/UIKit/AVFoundation)未经编译;.xcodeproj 已通过 plutil 解析与引用完整性校验(42 个对象无悬空引用), 但未在 Xcode 中实际打开过。
This commit is contained in:
@@ -0,0 +1,197 @@
|
||||
import SwiftUI
|
||||
import UniformTypeIdentifiers
|
||||
|
||||
struct HomeView: View {
|
||||
|
||||
/// 同一个 view 上挂多个 .fileImporter 会互相覆盖,只能有一个,
|
||||
/// 所以用这个枚举区分「选完文件之后要干什么」。
|
||||
private enum PickPurpose: Equatable {
|
||||
case peerSend
|
||||
case uploadToPC(PairingPayload)
|
||||
}
|
||||
|
||||
@StateObject private var model = TransferModel()
|
||||
@State private var pickPurpose: PickPurpose?
|
||||
|
||||
var body: some View {
|
||||
NavigationStack {
|
||||
content
|
||||
.navigationTitle("QFT 快传")
|
||||
.navigationBarTitleDisplayMode(.inline)
|
||||
}
|
||||
.fullScreenCover(isPresented: isScanning) {
|
||||
ScannerView(onFound: { model.handleScanned($0) }, onCancel: { model.cancel() })
|
||||
.ignoresSafeArea()
|
||||
}
|
||||
.fileImporter(isPresented: isPicking,
|
||||
allowedContentTypes: [UTType.item], allowsMultipleSelection: false) { result in
|
||||
let purpose = pickPurpose
|
||||
pickPurpose = nil
|
||||
guard case .success(let urls) = result, let url = urls.first else {
|
||||
model.reset()
|
||||
return
|
||||
}
|
||||
switch purpose {
|
||||
case .peerSend: model.startPeerSend(fileURL: url)
|
||||
case .uploadToPC(let pairing): model.startUpload(pairing, fileURL: url)
|
||||
case nil: break
|
||||
}
|
||||
}
|
||||
.onAppear { model.refreshReceivedFiles() }
|
||||
.onChange(of: model.stage) { _, stage in
|
||||
// 扫到 QFTPAIR2 之后才知道要选文件,所以选择器由 stage 驱动
|
||||
if case .pickFileForUpload(let pairing) = stage {
|
||||
pickPurpose = .uploadToPC(pairing)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private var isScanning: Binding<Bool> {
|
||||
Binding(get: { model.stage == .scanning }, set: { if !$0 { model.cancel() } })
|
||||
}
|
||||
|
||||
private var isPicking: Binding<Bool> {
|
||||
Binding(get: { pickPurpose != nil }, set: { if !$0 { pickPurpose = nil } })
|
||||
}
|
||||
|
||||
@ViewBuilder
|
||||
private var content: some View {
|
||||
switch model.stage {
|
||||
case .idle, .scanning, .pickFileForUpload:
|
||||
landing
|
||||
case .connecting(let message):
|
||||
StatusCard(icon: "antenna.radiowaves.left.and.right", title: message) {
|
||||
ProgressView()
|
||||
Button("取消", role: .cancel) { model.cancel() }
|
||||
}
|
||||
case .running(let message):
|
||||
StatusCard(icon: "arrow.left.arrow.right", title: message) {
|
||||
if let progress = model.progress {
|
||||
ProgressView(value: progress.fraction)
|
||||
Text("\(progress.readableSize) · \(progress.readableRate)")
|
||||
.font(.footnote.monospacedDigit())
|
||||
.foregroundStyle(.secondary)
|
||||
} else {
|
||||
ProgressView()
|
||||
}
|
||||
Button("取消", role: .cancel) { model.cancel() }
|
||||
}
|
||||
case .showingPeerCode(let pairing):
|
||||
peerCode(pairing)
|
||||
case .finished(let message, let url):
|
||||
StatusCard(icon: "checkmark.circle.fill", title: message) {
|
||||
if let url {
|
||||
Text(url.lastPathComponent).font(.footnote).foregroundStyle(.secondary)
|
||||
ShareLink(item: url) { Label("分享", systemImage: "square.and.arrow.up") }
|
||||
}
|
||||
Button("完成") { model.reset() }.buttonStyle(.borderedProminent)
|
||||
}
|
||||
case .failed(let message):
|
||||
StatusCard(icon: "exclamationmark.triangle.fill", title: "传输失败") {
|
||||
Text(message).font(.footnote).multilineTextAlignment(.center)
|
||||
.foregroundStyle(.secondary)
|
||||
Button("返回") { model.reset() }.buttonStyle(.borderedProminent)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private var landing: some View {
|
||||
List {
|
||||
Section {
|
||||
ActionRow(icon: "qrcode.viewfinder", title: "扫码",
|
||||
detail: "扫电脑上的二维码收发文件,或扫另一台 iPhone 的码接收") {
|
||||
model.beginScan()
|
||||
}
|
||||
ActionRow(icon: "iphone.gen3.radiowaves.left.and.right", title: "发给附近的 iPhone",
|
||||
detail: "选文件后显示二维码,对方扫一下即可,无需连同一个 Wi-Fi") {
|
||||
pickPurpose = .peerSend
|
||||
}
|
||||
} footer: {
|
||||
Text("与电脑互传需要手机和电脑连在同一个 Wi-Fi。iPhone 之间使用点对点直连,不经过路由器。")
|
||||
}
|
||||
|
||||
if !model.receivedFiles.isEmpty {
|
||||
Section("已接收") {
|
||||
ForEach(model.receivedFiles, id: \.self) { url in
|
||||
ShareLink(item: url) {
|
||||
Label(url.lastPathComponent, systemImage: "doc")
|
||||
.lineLimit(1)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func peerCode(_ pairing: PeerPairing) -> some View {
|
||||
VStack(spacing: 20) {
|
||||
Text("让对方用 QFT 扫这个码")
|
||||
.font(.headline)
|
||||
if let image = QRRenderer.image(from: pairing.encode()) {
|
||||
Image(uiImage: image)
|
||||
.interpolation(.none)
|
||||
.resizable()
|
||||
.scaledToFit()
|
||||
.frame(maxWidth: 300)
|
||||
.padding()
|
||||
.background(.white)
|
||||
.clipShape(RoundedRectangle(cornerRadius: 16))
|
||||
}
|
||||
VStack(spacing: 4) {
|
||||
Text(pairing.fileName).font(.subheadline).lineLimit(1)
|
||||
Text(TransferProgress.readable(pairing.fileSize))
|
||||
.font(.footnote).foregroundStyle(.secondary)
|
||||
}
|
||||
if let progress = model.progress {
|
||||
ProgressView(value: progress.fraction)
|
||||
.padding(.horizontal, 40)
|
||||
Text("\(progress.readableSize) · \(progress.readableRate)")
|
||||
.font(.footnote.monospacedDigit()).foregroundStyle(.secondary)
|
||||
} else {
|
||||
Label("等待对方扫码…", systemImage: "hourglass")
|
||||
.font(.footnote).foregroundStyle(.secondary)
|
||||
}
|
||||
Button("取消", role: .cancel) { model.cancel() }
|
||||
}
|
||||
.padding()
|
||||
}
|
||||
}
|
||||
|
||||
private struct ActionRow: View {
|
||||
let icon: String
|
||||
let title: String
|
||||
let detail: String
|
||||
let action: () -> Void
|
||||
|
||||
var body: some View {
|
||||
Button(action: action) {
|
||||
HStack(spacing: 14) {
|
||||
Image(systemName: icon)
|
||||
.font(.title2)
|
||||
.frame(width: 34)
|
||||
VStack(alignment: .leading, spacing: 3) {
|
||||
Text(title).font(.body.weight(.medium))
|
||||
Text(detail).font(.caption).foregroundStyle(.secondary)
|
||||
}
|
||||
}
|
||||
.padding(.vertical, 4)
|
||||
}
|
||||
.buttonStyle(.plain)
|
||||
}
|
||||
}
|
||||
|
||||
private struct StatusCard<Content: View>: View {
|
||||
let icon: String
|
||||
let title: String
|
||||
@ViewBuilder let content: Content
|
||||
|
||||
var body: some View {
|
||||
VStack(spacing: 18) {
|
||||
Image(systemName: icon).font(.system(size: 44))
|
||||
Text(title).font(.headline).multilineTextAlignment(.center)
|
||||
content
|
||||
}
|
||||
.padding(32)
|
||||
.frame(maxWidth: .infinity, maxHeight: .infinity)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import SwiftUI
|
||||
|
||||
@main
|
||||
struct QFTApp: App {
|
||||
var body: some Scene {
|
||||
WindowGroup {
|
||||
HomeView()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
import SwiftUI
|
||||
import AVFoundation
|
||||
|
||||
/// 二维码扫描。用 AVCaptureMetadataOutput 而不是 Vision:
|
||||
/// 硬件解码路径延迟更低,而且这里只需要识别静态配对码,
|
||||
/// 不需要 QFT2 光学链路那套 ROI 锁定与高频解码。
|
||||
struct ScannerView: UIViewControllerRepresentable {
|
||||
|
||||
/// 只在识别到我们认识的前缀时回调,且只回调一次。
|
||||
let onFound: (String) -> Void
|
||||
let onCancel: () -> Void
|
||||
|
||||
func makeCoordinator() -> Coordinator { Coordinator(onFound: onFound) }
|
||||
|
||||
func makeUIViewController(context: Context) -> ScannerController {
|
||||
let controller = ScannerController()
|
||||
controller.coordinator = context.coordinator
|
||||
controller.onCancel = onCancel
|
||||
return controller
|
||||
}
|
||||
|
||||
func updateUIViewController(_ controller: ScannerController, context: Context) {}
|
||||
|
||||
final class Coordinator: NSObject, AVCaptureMetadataOutputObjectsDelegate {
|
||||
private let onFound: (String) -> Void
|
||||
private var consumed = false
|
||||
|
||||
init(onFound: @escaping (String) -> Void) { self.onFound = onFound }
|
||||
|
||||
func metadataOutput(_ output: AVCaptureMetadataOutput,
|
||||
didOutput objects: [AVMetadataObject],
|
||||
from connection: AVCaptureConnection) {
|
||||
guard !consumed else { return }
|
||||
for object in objects {
|
||||
guard let readable = object as? AVMetadataMachineReadableCodeObject,
|
||||
readable.type == .qr, let text = readable.stringValue else { continue }
|
||||
guard PairingProtocol.isPairingText(text) || PeerPairing.isPeerText(text) else { continue }
|
||||
consumed = true
|
||||
UINotificationFeedbackGenerator().notificationOccurred(.success)
|
||||
DispatchQueue.main.async { self.onFound(text) }
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
final class ScannerController: UIViewController {
|
||||
|
||||
var coordinator: ScannerView.Coordinator?
|
||||
var onCancel: (() -> Void)?
|
||||
|
||||
private let session = AVCaptureSession()
|
||||
private var preview: AVCaptureVideoPreviewLayer?
|
||||
private let hintLabel = UILabel()
|
||||
|
||||
override func viewDidLoad() {
|
||||
super.viewDidLoad()
|
||||
view.backgroundColor = .black
|
||||
configureSession()
|
||||
configureOverlay()
|
||||
}
|
||||
|
||||
private func configureSession() {
|
||||
guard let device = AVCaptureDevice.default(.builtInWideAngleCamera, for: .video, position: .back),
|
||||
let input = try? AVCaptureDeviceInput(device: device),
|
||||
session.canAddInput(input) else {
|
||||
showFailure("无法打开相机")
|
||||
return
|
||||
}
|
||||
session.addInput(input)
|
||||
|
||||
let output = AVCaptureMetadataOutput()
|
||||
guard session.canAddOutput(output) else {
|
||||
showFailure("无法启动二维码识别")
|
||||
return
|
||||
}
|
||||
session.addOutput(output)
|
||||
output.setMetadataObjectsDelegate(coordinator, queue: .main)
|
||||
output.metadataObjectTypes = [.qr]
|
||||
|
||||
let layer = AVCaptureVideoPreviewLayer(session: session)
|
||||
layer.videoGravity = .resizeAspectFill
|
||||
layer.frame = view.bounds
|
||||
view.layer.insertSublayer(layer, at: 0)
|
||||
preview = layer
|
||||
}
|
||||
|
||||
private func configureOverlay() {
|
||||
hintLabel.text = "对准电脑或另一台 iPhone 上的二维码"
|
||||
hintLabel.textColor = .white
|
||||
hintLabel.font = .systemFont(ofSize: 15, weight: .medium)
|
||||
hintLabel.textAlignment = .center
|
||||
hintLabel.numberOfLines = 0
|
||||
hintLabel.translatesAutoresizingMaskIntoConstraints = false
|
||||
view.addSubview(hintLabel)
|
||||
|
||||
let cancel = UIButton(type: .system)
|
||||
cancel.setTitle("取消", for: .normal)
|
||||
cancel.setTitleColor(.white, for: .normal)
|
||||
cancel.titleLabel?.font = .systemFont(ofSize: 17, weight: .semibold)
|
||||
cancel.addTarget(self, action: #selector(cancelTapped), for: .touchUpInside)
|
||||
cancel.translatesAutoresizingMaskIntoConstraints = false
|
||||
view.addSubview(cancel)
|
||||
|
||||
NSLayoutConstraint.activate([
|
||||
hintLabel.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 32),
|
||||
hintLabel.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -32),
|
||||
hintLabel.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -96),
|
||||
cancel.centerXAnchor.constraint(equalTo: view.centerXAnchor),
|
||||
cancel.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -32),
|
||||
])
|
||||
}
|
||||
|
||||
@objc private func cancelTapped() { onCancel?() }
|
||||
|
||||
private func showFailure(_ message: String) {
|
||||
hintLabel.text = message
|
||||
}
|
||||
|
||||
override func viewWillAppear(_ animated: Bool) {
|
||||
super.viewWillAppear(animated)
|
||||
guard !session.isRunning else { return }
|
||||
// startRunning 会阻塞,必须离开主线程
|
||||
DispatchQueue.global(qos: .userInitiated).async { [session] in session.startRunning() }
|
||||
}
|
||||
|
||||
override func viewWillDisappear(_ animated: Bool) {
|
||||
super.viewWillDisappear(animated)
|
||||
guard session.isRunning else { return }
|
||||
DispatchQueue.global(qos: .userInitiated).async { [session] in session.stopRunning() }
|
||||
}
|
||||
|
||||
override func viewDidLayoutSubviews() {
|
||||
super.viewDidLayoutSubviews()
|
||||
preview?.frame = view.bounds
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,242 @@
|
||||
import SwiftUI
|
||||
import CoreImage.CIFilterBuiltins
|
||||
|
||||
@MainActor
|
||||
final class TransferModel: ObservableObject {
|
||||
|
||||
enum Stage: Equatable {
|
||||
case idle
|
||||
case scanning
|
||||
/// 扫到 QFTPAIR2:需要用户挑一个文件传给电脑
|
||||
case pickFileForUpload(PairingPayload)
|
||||
case connecting(String)
|
||||
case running(String)
|
||||
case showingPeerCode(PeerPairing)
|
||||
case finished(String, URL?)
|
||||
case failed(String)
|
||||
}
|
||||
|
||||
@Published private(set) var stage: Stage = .idle
|
||||
@Published private(set) var progress: TransferProgress?
|
||||
@Published private(set) var receivedFiles: [URL] = []
|
||||
|
||||
private var task: Task<Void, Never>?
|
||||
private var sender: PeerSender?
|
||||
private var scopedURL: URL?
|
||||
|
||||
private let deviceName = DeviceInfo.name
|
||||
|
||||
// MARK: - 入口
|
||||
|
||||
func beginScan() { stage = .scanning }
|
||||
|
||||
func cancel() {
|
||||
task?.cancel()
|
||||
task = nil
|
||||
sender?.stop()
|
||||
sender = nil
|
||||
releaseScope()
|
||||
progress = nil
|
||||
stage = .idle
|
||||
}
|
||||
|
||||
func reset() {
|
||||
progress = nil
|
||||
stage = .idle
|
||||
refreshReceivedFiles()
|
||||
}
|
||||
|
||||
/// 扫到码之后的统一分发
|
||||
func handleScanned(_ text: String) {
|
||||
if let peer = PeerPairing.parse(text) {
|
||||
startPeerReceive(peer)
|
||||
return
|
||||
}
|
||||
guard let pairing = PairingProtocol.parse(text) else {
|
||||
stage = .failed("这不是 QFT 的二维码,或二维码里的地址不是局域网地址。")
|
||||
return
|
||||
}
|
||||
switch pairing.direction {
|
||||
case .downloadToPhone: startDownload(pairing)
|
||||
case .uploadToPC: stage = .pickFileForUpload(pairing)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - 电脑 → 手机
|
||||
|
||||
private func startDownload(_ pairing: PairingPayload) {
|
||||
stage = .connecting("正在找 \(pairing.pcName)…")
|
||||
task = Task {
|
||||
do {
|
||||
let host = try await HostDiscovery(pairing: pairing, deviceName: deviceName).locate()
|
||||
guard !Task.isCancelled else { return }
|
||||
stage = .running("正在从 \(pairing.pcName) 接收 \(pairing.fileName ?? "文件")")
|
||||
let client = DownloadClient(host: host, pairing: pairing, deviceName: deviceName)
|
||||
let saved = try await client.run { [weak self] value in
|
||||
Task { @MainActor in self?.progress = value }
|
||||
}
|
||||
finish("已保存到「文件」App 的 QFT 文件夹", saved)
|
||||
} catch {
|
||||
fail(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - 手机 → 电脑
|
||||
|
||||
func startUpload(_ pairing: PairingPayload, fileURL: URL) {
|
||||
guard claimScope(fileURL) else {
|
||||
stage = .failed("没有权限读取这个文件,请换一个位置再试。")
|
||||
return
|
||||
}
|
||||
stage = .connecting("正在找 \(pairing.pcName)…")
|
||||
task = Task {
|
||||
defer { releaseScope() }
|
||||
do {
|
||||
let host = try await HostDiscovery(pairing: pairing, deviceName: deviceName).locate()
|
||||
guard !Task.isCancelled else { return }
|
||||
stage = .running("正在发送 \(fileURL.lastPathComponent) 到 \(pairing.pcName)")
|
||||
let client = UploadClient(host: host, pairing: pairing, deviceName: deviceName)
|
||||
_ = try await client.run(fileURL: fileURL) { [weak self] value in
|
||||
Task { @MainActor in self?.progress = value }
|
||||
}
|
||||
finish("已发送到 \(pairing.pcName)", nil)
|
||||
} catch {
|
||||
fail(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - iPhone ↔ iPhone(隔空投送式)
|
||||
|
||||
func startPeerSend(fileURL: URL) {
|
||||
guard claimScope(fileURL) else {
|
||||
stage = .failed("没有权限读取这个文件,请换一个位置再试。")
|
||||
return
|
||||
}
|
||||
stage = .connecting("正在准备…")
|
||||
task = Task {
|
||||
defer { releaseScope() }
|
||||
do {
|
||||
let sender = PeerSender(fileURL: fileURL, deviceName: deviceName)
|
||||
// start() 里要完整读一遍文件算摘要,别卡住主线程
|
||||
let pairing = try await Task.detached { try sender.start() }.value
|
||||
guard !Task.isCancelled else { sender.stop(); return }
|
||||
self.sender = sender
|
||||
stage = .showingPeerCode(pairing)
|
||||
try await sender.waitAndSend { [weak self] value in
|
||||
Task { @MainActor in self?.progress = value }
|
||||
}
|
||||
finish("已发送给对方", nil)
|
||||
} catch {
|
||||
fail(error)
|
||||
}
|
||||
sender?.stop()
|
||||
sender = nil
|
||||
}
|
||||
}
|
||||
|
||||
private func startPeerReceive(_ pairing: PeerPairing) {
|
||||
stage = .connecting("正在连接 \(pairing.senderName)…")
|
||||
task = Task {
|
||||
do {
|
||||
let directory = try DownloadClient.defaultDestinationDirectory()
|
||||
let receiver = PeerReceiver(pairing: pairing, destinationDirectory: directory)
|
||||
stage = .running("正在接收 \(pairing.fileName)")
|
||||
let saved = try await receiver.run { [weak self] value in
|
||||
Task { @MainActor in self?.progress = value }
|
||||
}
|
||||
finish("已保存到「文件」App 的 QFT 文件夹", saved)
|
||||
} catch {
|
||||
fail(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - 收尾
|
||||
|
||||
private func finish(_ message: String, _ url: URL?) {
|
||||
progress = nil
|
||||
stage = .finished(message, url)
|
||||
refreshReceivedFiles()
|
||||
}
|
||||
|
||||
private func fail(_ error: Error) {
|
||||
guard !(error is CancellationError) else { return }
|
||||
progress = nil
|
||||
stage = .failed(error.localizedDescription)
|
||||
}
|
||||
|
||||
func refreshReceivedFiles() {
|
||||
guard let directory = try? DownloadClient.defaultDestinationDirectory(),
|
||||
let entries = try? FileManager.default.contentsOfDirectory(
|
||||
at: directory, includingPropertiesForKeys: [.contentModificationDateKey]) else {
|
||||
receivedFiles = []
|
||||
return
|
||||
}
|
||||
receivedFiles = entries
|
||||
.filter { $0.pathExtension != "qftpart" }
|
||||
.sorted { lhs, rhs in
|
||||
let l = (try? lhs.resourceValues(forKeys: [.contentModificationDateKey]))?
|
||||
.contentModificationDate ?? .distantPast
|
||||
let r = (try? rhs.resourceValues(forKeys: [.contentModificationDateKey]))?
|
||||
.contentModificationDate ?? .distantPast
|
||||
return l > r
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - 安全作用域
|
||||
|
||||
/// 文件选择器给的 URL 属于其他进程的沙盒,读之前必须声明作用域,
|
||||
/// 而且整个传输期间都要持有。
|
||||
private func claimScope(_ url: URL) -> Bool {
|
||||
releaseScope()
|
||||
guard url.startAccessingSecurityScopedResource() else { return false }
|
||||
scopedURL = url
|
||||
return true
|
||||
}
|
||||
|
||||
private func releaseScope() {
|
||||
scopedURL?.stopAccessingSecurityScopedResource()
|
||||
scopedURL = nil
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - 二维码渲染
|
||||
|
||||
enum QRRenderer {
|
||||
/// 配对码只有几百字节,用 M 级纠错换取更好的首次识别率。
|
||||
static func image(from text: String) -> UIImage? {
|
||||
let filter = CIFilter.qrCodeGenerator()
|
||||
filter.message = Data(text.utf8)
|
||||
filter.correctionLevel = "M"
|
||||
guard let output = filter.outputImage else { return nil }
|
||||
// 放大用最近邻,避免插值把模块边缘糊掉
|
||||
let scaled = output.transformed(by: CGAffineTransform(scaleX: 12, y: 12))
|
||||
let context = CIContext()
|
||||
guard let cgImage = context.createCGImage(scaled, from: scaled.extent) else { return nil }
|
||||
return UIImage(cgImage: cgImage)
|
||||
}
|
||||
}
|
||||
|
||||
extension TransferProgress {
|
||||
var readableRate: String {
|
||||
let units = ["B/s", "KB/s", "MB/s", "GB/s"]
|
||||
var value = bytesPerSecond
|
||||
var index = 0
|
||||
while value >= 1024, index < units.count - 1 { value /= 1024; index += 1 }
|
||||
return String(format: "%.1f %@", value, units[index])
|
||||
}
|
||||
|
||||
var readableSize: String {
|
||||
Self.readable(completed) + " / " + Self.readable(total)
|
||||
}
|
||||
|
||||
static func readable(_ bytes: UInt64) -> String {
|
||||
let units = ["B", "KB", "MB", "GB"]
|
||||
var value = Double(bytes)
|
||||
var index = 0
|
||||
while value >= 1024, index < units.count - 1 { value /= 1024; index += 1 }
|
||||
return String(format: index == 0 ? "%.0f %@" : "%.1f %@", value, units[index])
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user