Skip to content

Linux + iPhone Continuity / iMessage / SMS

feat(ios): send multiple photos

Zack Bartel64d083071922
diff --git a/apple/Tether/ViewModels/TetherViewModel.swift b/apple/Tether/ViewModels/TetherViewModel.swift
index 5d76cea..34b3ff7 100644
--- a/apple/Tether/ViewModels/TetherViewModel.swift
+++ b/apple/Tether/ViewModels/TetherViewModel.swift
@@ -11,6 +11,7 @@ import SwiftUI
import UniformTypeIdentifiers
import AVFoundation
import UIKit
+import PhotosUI
import TetherFramework
internal import Network
@@ -67,7 +68,7 @@ struct FileTransfer: Identifiable {
let id: String // transfer_id
var filename: String
- let totalSize: Int64
+ var totalSize: Int64
var direction: Direction
var bytesTransferred: Int64 = 0
var isComplete = false
@@ -381,97 +382,159 @@ final class TetherViewModel {
// MARK: - File Transfer
- // Send a file to the daemon using its URL.
- func sendFile(url: URL) {
- let isSecurityScoped = url.startAccessingSecurityScopedResource()
- let filename = url.lastPathComponent
+ // A file in a batch: its name and how to read it when its turn comes.
+ private typealias BatchItem = (filename: String, load: @Sendable () async throws -> Data)
+
+ // Send files picked in the document picker.
+ func sendFiles(urls: [URL]) {
+ sendBatch(urls.map { url -> BatchItem in
+ (url.lastPathComponent, {
+ let isSecurityScoped = url.startAccessingSecurityScopedResource()
+ defer { if isSecurityScoped { url.stopAccessingSecurityScopedResource() } }
+ return try Data(contentsOf: url)
+ })
+ })
+ }
+
+ // Send photos picked in the photo library, as their original encoding.
+ func sendPhotos(_ items: [PhotosPickerItem]) {
+ sendBatch(items.map { item -> BatchItem in
+ let ext = item.supportedContentTypes.first?.preferredFilenameExtension ?? "jpg"
+ return ("Image_\(UUID().uuidString.prefix(6)).\(ext)", {
+ guard let data = try await item.loadTransferable(type: Data.self) else {
+ throw CocoaError(.fileReadUnknown)
+ }
+ return data
+ })
+ })
+ }
+
+ // Send raw data to the daemon. A clipboard transfer stays out of the Files tab.
+ func sendFile(data fileData: Data, filename: String, clipboard: String? = nil) {
+ let transferId = UUID().uuidString
+ if clipboard == nil {
+ activeTransfers.append(FileTransfer(
+ id: transferId,
+ filename: filename,
+ totalSize: Int64(fileData.count),
+ direction: .outgoing
+ ))
+ }
Task.detached { [weak self] in
guard let self else { return }
- defer { if isSecurityScoped { url.stopAccessingSecurityScopedResource() } }
do {
- let fileData = try Data(contentsOf: url)
- await self.sendFile(data: fileData, filename: filename)
+ try await self.streamFile(fileData, filename: filename, transferId: transferId, clipboard: clipboard)
} catch {
await MainActor.run {
- self.errorMessage = "File transfer failed: \(error.localizedDescription)"
+ self.markTransferFailed(transferId)
+ self.errorMessage = "File transfer error from daemon: \(error.localizedDescription)"
}
}
}
}
- // Send raw data to the daemon. A clipboard transfer stays out of the Files tab.
- func sendFile(data fileData: Data, filename: String, clipboard: String? = nil) {
- let transferId = UUID().uuidString
- let totalSize = Int64(fileData.count)
+ // Send files one after another so only one is in memory at a time.
+ // Every row shows up right away; a file that can't be read fails alone.
+ private func sendBatch(_ items: [BatchItem]) {
+ guard !items.isEmpty else { return }
+ let transferIds = items.map { item in
+ let transferId = UUID().uuidString
+ activeTransfers.append(FileTransfer(
+ id: transferId,
+ filename: item.filename,
+ totalSize: 0,
+ direction: .outgoing
+ ))
+ return transferId
+ }
Task.detached { [weak self] in
guard let self else { return }
- do {
- if clipboard == nil {
- await MainActor.run {
- let transfer = FileTransfer(
- id: transferId,
- filename: filename,
- totalSize: totalSize,
- direction: .outgoing
- )
- self.activeTransfers.append(transfer)
- }
- }
-
- // Send file_start
- await MainActor.run {
- self.connection.send(.fileStart(
- filename: filename,
- size: totalSize,
- transferId: transferId,
- clipboard: clipboard
- ))
+ var failures = 0
+ for (index, (item, transferId)) in zip(items, transferIds).enumerated() {
+ // The connection drops sends silently once it's gone, so stop here.
+ guard await MainActor.run(body: { self.appState == .connected }) else {
+ await MainActor.run { transferIds[index...].forEach(self.markTransferFailed) }
+ failures += transferIds.count - index
+ break
}
- // Send chunks
- var offset = 0
- var chunkIndex = 0
- while offset < fileData.count {
- let end = min(offset + self.fileChunkSize, fileData.count)
- let chunk = fileData[offset..<end]
- let base64 = chunk.base64EncodedString()
- let index = chunkIndex
-
+ do {
+ let fileData = try await item.load()
await MainActor.run {
- self.connection.send(.fileChunk(
- transferId: transferId,
- chunkIndex: index,
- data: base64
- ))
-
if let idx = self.activeTransfers.firstIndex(where: { $0.id == transferId }) {
- self.activeTransfers[idx].bytesTransferred = Int64(end)
+ self.activeTransfers[idx].totalSize = Int64(fileData.count)
}
}
+ try await self.streamFile(fileData, filename: item.filename, transferId: transferId, clipboard: nil)
+ } catch {
+ await MainActor.run { self.markTransferFailed(transferId) }
+ failures += 1
+ }
+ }
- offset = end
- chunkIndex += 1
+ if failures > 0 {
+ let message = items.count == 1
+ ? "Could not send \(items[0].filename)."
+ : "\(failures) of \(items.count) files could not be sent."
+ await MainActor.run { self.errorMessage = message }
+ }
+ }
+ }
- // Small delay to avoid overwhelming the connection
- try await Task.sleep(for: .milliseconds(10))
- }
+ // Stream one file to the daemon as file_start, paced file_chunks, file_end.
+ private nonisolated func streamFile(
+ _ fileData: Data,
+ filename: String,
+ transferId: String,
+ clipboard: String?
+ ) async throws {
+ await MainActor.run {
+ self.connection.send(.fileStart(
+ filename: filename,
+ size: Int64(fileData.count),
+ transferId: transferId,
+ clipboard: clipboard
+ ))
+ }
- // Send file_end
- await MainActor.run {
- self.connection.send(.fileEnd(transferId: transferId))
- }
- } catch {
- await MainActor.run {
- if let idx = self.activeTransfers.firstIndex(where: { $0.id == transferId }) {
- self.activeTransfers[idx].failed = true
- }
- self.errorMessage = "File transfer error from daemon: \(error.localizedDescription)"
+ var offset = 0
+ var chunkIndex = 0
+ while offset < fileData.count {
+ let end = min(offset + fileChunkSize, fileData.count)
+ let base64 = fileData[offset..<end].base64EncodedString()
+ let index = chunkIndex
+
+ await MainActor.run {
+ self.connection.send(.fileChunk(
+ transferId: transferId,
+ chunkIndex: index,
+ data: base64
+ ))
+
+ if let idx = self.activeTransfers.firstIndex(where: { $0.id == transferId }) {
+ self.activeTransfers[idx].bytesTransferred = Int64(end)
}
}
+
+ offset = end
+ chunkIndex += 1
+
+ // Small delay to avoid overwhelming the connection
+ try await Task.sleep(for: .milliseconds(10))
+ }
+
+ await MainActor.run {
+ self.connection.send(.fileEnd(transferId: transferId))
+ }
+ }
+
+ private func markTransferFailed(_ transferId: String) {
+ if let idx = activeTransfers.firstIndex(where: { $0.id == transferId }) {
+ activeTransfers[idx].failed = true
}
}
@@ -750,11 +813,15 @@ final class TetherViewModel {
daemonCameraPort = message.features?.contains("camera") == true ? message.port : nil
case .fileStatus:
- if let transferId = message.transferId, message.status == "success" {
- if let idx = activeTransfers.firstIndex(where: { $0.id == transferId }) {
+ if let transferId = message.transferId,
+ let idx = activeTransfers.firstIndex(where: { $0.id == transferId }) {
+ if message.status == "success" {
var transfer = activeTransfers.remove(at: idx)
transfer.isComplete = true
completedTransfers.insert(transfer, at: 0)
+ } else {
+ activeTransfers[idx].failed = true
+ errorMessage = "Your computer could not save \(activeTransfers[idx].filename)."
}
}
diff --git a/apple/Tether/Views/FilesView.swift b/apple/Tether/Views/FilesView.swift
index a6882a7..a82f460 100644
--- a/apple/Tether/Views/FilesView.swift
+++ b/apple/Tether/Views/FilesView.swift
@@ -14,7 +14,7 @@ struct FilesView: View {
@Environment(\.openURL) private var openURL
@State private var showDocumentPicker = false
- @State private var selectedPhotoItem: PhotosPickerItem? = nil
+ @State private var selectedPhotoItems: [PhotosPickerItem] = []
var body: some View {
NavigationStack {
@@ -39,11 +39,11 @@ struct FilesView: View {
.accessibilityLabel("Open Received Files")
if viewModel.appState == .connected {
- PhotosPicker(selection: $selectedPhotoItem, matching: .images, preferredItemEncoding: .current) {
+ PhotosPicker(selection: $selectedPhotoItems, maxSelectionCount: 50, selectionBehavior: .ordered, matching: .images, preferredItemEncoding: .current) {
Image(systemName: "photo.on.rectangle")
.foregroundStyle(.teal)
}
- .accessibilityLabel("Send a Photo")
+ .accessibilityLabel("Send Photos")
Button {
showDocumentPicker = true
} label: {
@@ -58,30 +58,20 @@ struct FilesView: View {
.fileImporter(
isPresented: $showDocumentPicker,
allowedContentTypes: [.data],
- allowsMultipleSelection: false
+ allowsMultipleSelection: true
) { result in
switch result {
case .success(let urls):
- if let url = urls.first {
- viewModel.sendFile(url: url)
- }
+ viewModel.sendFiles(urls: urls)
case .failure(let error):
viewModel.errorMessage = "File selection failed: \(error.localizedDescription)"
}
}
- .onChange(of: selectedPhotoItem) { _, newItem in
- guard let newItem else { return }
-
- Task {
- if let data = try? await newItem.loadTransferable(type: Data.self) {
- let ext = newItem.supportedContentTypes.first?.preferredFilenameExtension ?? "jpg"
- let defaultName = "Image_\(UUID().uuidString.prefix(6)).\(ext)"
- viewModel.sendFile(data: data, filename: defaultName)
- } else {
- viewModel.errorMessage = "Could not read photo data."
- }
- selectedPhotoItem = nil
- }
+ .onChange(of: selectedPhotoItems) { _, items in
+ // Clearing the selection fires this again with an empty array.
+ guard !items.isEmpty else { return }
+ selectedPhotoItems = []
+ viewModel.sendPhotos(items)
}
}
}
@@ -158,7 +148,7 @@ struct FilesView: View {
.buttonStyle(.plain)
// Send Photo Button
- PhotosPicker(selection: $selectedPhotoItem, matching: .images, preferredItemEncoding: .current, photoLibrary: .shared()) {
+ PhotosPicker(selection: $selectedPhotoItems, maxSelectionCount: 50, selectionBehavior: .ordered, matching: .images, preferredItemEncoding: .current, photoLibrary: .shared()) {
HStack(spacing: 14) {
ZStack {
Circle()
@@ -178,7 +168,7 @@ struct FilesView: View {
.accessibilityHidden(true)
VStack(alignment: .leading, spacing: 2) {
- Text("Send a Photo")
+ Text("Send Photos")
.font(.body.weight(.semibold))
.foregroundStyle(.primary)
diff --git a/apple/TetherFramework/Sources/TetherFramework/ShareSender.swift b/apple/TetherFramework/Sources/TetherFramework/ShareSender.swift
index a5bc40c..71b8c96 100644
--- a/apple/TetherFramework/Sources/TetherFramework/ShareSender.swift
+++ b/apple/TetherFramework/Sources/TetherFramework/ShareSender.swift
@@ -267,9 +267,12 @@ public actor ShareSender {
guard !resumed else { return }
switch message.parsedCommand {
case .fileStatus:
- if message.transferId == transferId, message.status == "success" {
- resumed = true
+ guard message.transferId == transferId else { break }
+ resumed = true
+ if message.status == "success" {
continuation.resume(returning: .success(()))
+ } else {
+ continuation.resume(returning: .failure(ShareSenderError.fileTransferFailed("Your computer could not save \(filename).")))
}
case .error:
resumed = true
diff --git a/docs/PROTOCOL.md b/docs/PROTOCOL.md
index c29c58c..ad12abc 100644
--- a/docs/PROTOCOL.md
+++ b/docs/PROTOCOL.md
@@ -179,6 +179,8 @@ Tether supports streaming large binary files seamlessly through JSON using Base6
}
```
+If the file could not be saved (for example it arrived short of the size given in `file_start`), `status` is `"error"` and the partial file is discarded.
+
For local Unix clients, `tetherd` returns `file_status` once the stream has been forwarded to at least one connected TCP client. If no mobile client is connected, the daemon returns:
```json