fix(swift-ios): stabilize photo attachments
This commit is contained in:
3 files changed
+25
-181
No files matched your search
@@ -1,6 +1,5 @@
|
||||
import ImageIO
|
||||
import PhotosUI
|
||||
import OSLog
|
||||
import SwiftUI
|
||||
import UniformTypeIdentifiers
|
||||
import UIKit
|
||||
@@ -50,6 +49,7 @@ struct FeatureImageAttachmentPicker: View {
|
||||
|
||||
@State private var isAttachmentSourcePresented = false
|
||||
@State private var isPhotoLibraryPresented = false
|
||||
@State private var photoSelections: [PhotosPickerItem] = []
|
||||
@State private var isCameraPresented = false
|
||||
@State private var isFileImporterPresented = false
|
||||
@State private var sourcePresentationTask: Task<Void, Never>?
|
||||
@@ -90,21 +90,13 @@ struct FeatureImageAttachmentPicker: View {
|
||||
Button("Files") { present(.files) }
|
||||
Button("Cancel", role: .cancel) {}
|
||||
}
|
||||
.fullScreenCover(isPresented: $isPhotoLibraryPresented) {
|
||||
FeaturePhotoLibraryPicker(
|
||||
maximumCount: max(1, remainingCount),
|
||||
onSelect: { images in
|
||||
isPhotoLibraryPresented = false
|
||||
loadPhotoSelections(images)
|
||||
},
|
||||
onFailure: { message in
|
||||
isPhotoLibraryPresented = false
|
||||
errorMessage = message
|
||||
},
|
||||
onCancel: { isPhotoLibraryPresented = false }
|
||||
)
|
||||
.ignoresSafeArea()
|
||||
}
|
||||
.photosPicker(
|
||||
isPresented: $isPhotoLibraryPresented,
|
||||
selection: $photoSelections,
|
||||
maxSelectionCount: max(1, remainingCount),
|
||||
matching: .images,
|
||||
preferredItemEncoding: .compatible
|
||||
)
|
||||
.fullScreenCover(isPresented: $isCameraPresented) {
|
||||
FeatureCameraPicker(
|
||||
onCapture: loadCapturedImage,
|
||||
@@ -132,6 +124,9 @@ struct FeatureImageAttachmentPicker: View {
|
||||
.onDisappear {
|
||||
sourcePresentationTask?.cancel()
|
||||
}
|
||||
.onChange(of: photoSelections) { _, selections in
|
||||
loadPhotoSelections(selections)
|
||||
}
|
||||
}
|
||||
|
||||
private var remainingCount: Int {
|
||||
@@ -174,16 +169,20 @@ struct FeatureImageAttachmentPicker: View {
|
||||
}
|
||||
}
|
||||
|
||||
private func loadPhotoSelections(_ images: [Data]) {
|
||||
guard !images.isEmpty, canAdd else { return }
|
||||
let selected = Array(images.prefix(remainingCount))
|
||||
private func loadPhotoSelections(_ selections: [PhotosPickerItem]) {
|
||||
guard !selections.isEmpty, canAdd else { return }
|
||||
let selected = Array(selections.prefix(remainingCount))
|
||||
photoSelections = []
|
||||
let firstOrdinal = attachments.count + preparationState.pendingItemCount + 1
|
||||
let operation = preparationState.begin(itemCount: selected.count)
|
||||
|
||||
Task {
|
||||
defer { preparationState.finish(operation) }
|
||||
for (offset, data) in selected.enumerated() {
|
||||
for (offset, item) in selected.enumerated() {
|
||||
do {
|
||||
guard let data = try await item.loadTransferable(type: Data.self) else {
|
||||
throw FeatureImageAttachmentError.invalidImage
|
||||
}
|
||||
try await appendImage(data, ordinal: firstOrdinal + offset)
|
||||
} catch {
|
||||
errorMessage = error.localizedDescription
|
||||
@@ -251,125 +250,6 @@ struct FeatureImageAttachmentPicker: View {
|
||||
}
|
||||
}
|
||||
|
||||
struct FeaturePhotoLibraryItem: @unchecked Sendable {
|
||||
let provider: NSItemProvider
|
||||
|
||||
func loadData() async throws -> Data {
|
||||
guard let typeIdentifier = provider.registeredTypeIdentifiers.first(where: { identifier in
|
||||
UTType(identifier)?.conforms(to: .image) == true
|
||||
}) else {
|
||||
throw FeatureImageAttachmentError.invalidImage
|
||||
}
|
||||
|
||||
return try await withCheckedThrowingContinuation { continuation in
|
||||
provider.loadDataRepresentation(forTypeIdentifier: typeIdentifier) { data, error in
|
||||
if let data {
|
||||
continuation.resume(returning: data)
|
||||
} else {
|
||||
continuation.resume(
|
||||
throwing: error ?? FeatureImageAttachmentError.encodingFailed
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private struct FeaturePhotoLibraryPicker: UIViewControllerRepresentable {
|
||||
let maximumCount: Int
|
||||
let onSelect: ([Data]) -> Void
|
||||
let onFailure: (String) -> Void
|
||||
let onCancel: () -> Void
|
||||
|
||||
func makeCoordinator() -> Coordinator {
|
||||
Coordinator(onSelect: onSelect, onFailure: onFailure, onCancel: onCancel)
|
||||
}
|
||||
|
||||
func makeUIViewController(context: Context) -> PHPickerViewController {
|
||||
var configuration = PHPickerConfiguration(photoLibrary: .shared())
|
||||
configuration.filter = .images
|
||||
configuration.selectionLimit = maximumCount
|
||||
// The composer always normalizes uploads to JPEG, so asking Photos for
|
||||
// a compatible representation avoids slow RAW/HEIF materialization.
|
||||
configuration.preferredAssetRepresentationMode = .compatible
|
||||
let controller = PHPickerViewController(configuration: configuration)
|
||||
controller.delegate = context.coordinator
|
||||
return controller
|
||||
}
|
||||
|
||||
func updateUIViewController(_ controller: PHPickerViewController, context: Context) {}
|
||||
|
||||
final class Coordinator: NSObject, PHPickerViewControllerDelegate {
|
||||
private let onSelect: ([Data]) -> Void
|
||||
private let onFailure: (String) -> Void
|
||||
private let onCancel: () -> Void
|
||||
private var didFinish = false
|
||||
|
||||
init(
|
||||
onSelect: @escaping ([Data]) -> Void,
|
||||
onFailure: @escaping (String) -> Void,
|
||||
onCancel: @escaping () -> Void
|
||||
) {
|
||||
self.onSelect = onSelect
|
||||
self.onFailure = onFailure
|
||||
self.onCancel = onCancel
|
||||
}
|
||||
|
||||
func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {
|
||||
guard !didFinish else { return }
|
||||
didFinish = true
|
||||
guard !results.isEmpty else {
|
||||
Task { @MainActor in
|
||||
await Task.yield()
|
||||
onCancel()
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// Keep the picker and its item providers alive until Photos has
|
||||
// materialized every selection. Dismissing the SwiftUI cover from
|
||||
// inside this delegate callback can tear down PhotosUI while its
|
||||
// provider transition is still in flight.
|
||||
picker.view.isUserInteractionEnabled = false
|
||||
let activity = UIActivityIndicatorView(style: .large)
|
||||
activity.translatesAutoresizingMaskIntoConstraints = false
|
||||
activity.startAnimating()
|
||||
picker.view.addSubview(activity)
|
||||
NSLayoutConstraint.activate([
|
||||
activity.centerXAnchor.constraint(equalTo: picker.view.centerXAnchor),
|
||||
activity.centerYAnchor.constraint(equalTo: picker.view.centerYAnchor),
|
||||
])
|
||||
|
||||
let items = results.map { FeaturePhotoLibraryItem(provider: $0.itemProvider) }
|
||||
Task { @MainActor in
|
||||
var images: [Data] = []
|
||||
var firstError: Error?
|
||||
for item in items {
|
||||
do {
|
||||
let data = try await item.loadData()
|
||||
images.append(data)
|
||||
} catch {
|
||||
firstError = firstError ?? error
|
||||
Self.logger.error(
|
||||
"Photo selection materialization failed: \(error.localizedDescription, privacy: .private)"
|
||||
)
|
||||
}
|
||||
}
|
||||
if images.isEmpty, let firstError {
|
||||
onFailure(firstError.localizedDescription)
|
||||
} else {
|
||||
onSelect(images)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static let logger = Logger(
|
||||
subsystem: Bundle.main.bundleIdentifier ?? "codes.t3.swift-ios",
|
||||
category: "Attachments"
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
struct FeatureAttachmentStrip: View {
|
||||
@Binding var attachments: [FeatureDraftAttachment]
|
||||
|
||||
|
||||
@@ -617,7 +617,7 @@
|
||||
ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;
|
||||
CODE_SIGN_ENTITLEMENTS = Extensions/Shared/T3Code.entitlements;
|
||||
CODE_SIGN_STYLE = Automatic;
|
||||
CURRENT_PROJECT_VERSION = 15;
|
||||
CURRENT_PROJECT_VERSION = 16;
|
||||
ENABLE_PREVIEWS = YES;
|
||||
GENERATE_INFOPLIST_FILE = YES;
|
||||
INFOPLIST_FILE = Resources/Info.plist;
|
||||
@@ -674,7 +674,7 @@
|
||||
ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;
|
||||
CODE_SIGN_ENTITLEMENTS = Extensions/Shared/T3Code.entitlements;
|
||||
CODE_SIGN_STYLE = Automatic;
|
||||
CURRENT_PROJECT_VERSION = 15;
|
||||
CURRENT_PROJECT_VERSION = 16;
|
||||
GENERATE_INFOPLIST_FILE = YES;
|
||||
INFOPLIST_FILE = Resources/Info.plist;
|
||||
INFOPLIST_KEY_CFBundleDisplayName = "T3 Code SwiftUI";
|
||||
@@ -764,7 +764,7 @@
|
||||
APPLICATION_EXTENSION_API_ONLY = YES;
|
||||
CODE_SIGN_ENTITLEMENTS = Extensions/Widgets/T3CodeWidgets.entitlements;
|
||||
CODE_SIGN_STYLE = Automatic;
|
||||
CURRENT_PROJECT_VERSION = 15;
|
||||
CURRENT_PROJECT_VERSION = 16;
|
||||
GENERATE_INFOPLIST_FILE = YES;
|
||||
INFOPLIST_FILE = Extensions/Widgets/Info.plist;
|
||||
INFOPLIST_KEY_ITSAppUsesNonExemptEncryption = NO;
|
||||
@@ -795,7 +795,7 @@
|
||||
APPLICATION_EXTENSION_API_ONLY = YES;
|
||||
CODE_SIGN_ENTITLEMENTS = Extensions/Widgets/T3CodeWidgets.entitlements;
|
||||
CODE_SIGN_STYLE = Automatic;
|
||||
CURRENT_PROJECT_VERSION = 15;
|
||||
CURRENT_PROJECT_VERSION = 16;
|
||||
GENERATE_INFOPLIST_FILE = YES;
|
||||
INFOPLIST_FILE = Extensions/Widgets/Info.plist;
|
||||
INFOPLIST_KEY_ITSAppUsesNonExemptEncryption = NO;
|
||||
@@ -828,7 +828,7 @@
|
||||
APPLICATION_EXTENSION_API_ONLY = YES;
|
||||
CODE_SIGN_ENTITLEMENTS = Extensions/Share/T3CodeShare.entitlements;
|
||||
CODE_SIGN_STYLE = Automatic;
|
||||
CURRENT_PROJECT_VERSION = 15;
|
||||
CURRENT_PROJECT_VERSION = 16;
|
||||
GENERATE_INFOPLIST_FILE = YES;
|
||||
INFOPLIST_FILE = Extensions/Share/Info.plist;
|
||||
INFOPLIST_KEY_ITSAppUsesNonExemptEncryption = NO;
|
||||
@@ -859,7 +859,7 @@
|
||||
APPLICATION_EXTENSION_API_ONLY = YES;
|
||||
CODE_SIGN_ENTITLEMENTS = Extensions/Share/T3CodeShare.entitlements;
|
||||
CODE_SIGN_STYLE = Automatic;
|
||||
CURRENT_PROJECT_VERSION = 15;
|
||||
CURRENT_PROJECT_VERSION = 16;
|
||||
GENERATE_INFOPLIST_FILE = YES;
|
||||
INFOPLIST_FILE = Extensions/Share/Info.plist;
|
||||
INFOPLIST_KEY_ITSAppUsesNonExemptEncryption = NO;
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
import Foundation
|
||||
import Testing
|
||||
import UniformTypeIdentifiers
|
||||
import UIKit
|
||||
@testable import T3Code
|
||||
|
||||
@Suite("Attachment preparation")
|
||||
@@ -73,38 +71,4 @@ struct AttachmentPreparationTests {
|
||||
preparationState: state
|
||||
))
|
||||
}
|
||||
|
||||
@Test
|
||||
func photoLibraryItemLoadsItsConcreteImageRepresentation() async throws {
|
||||
let expected = Data([0x89, 0x50, 0x4E, 0x47])
|
||||
let provider = NSItemProvider()
|
||||
provider.registerDataRepresentation(
|
||||
forTypeIdentifier: UTType.png.identifier,
|
||||
visibility: .all
|
||||
) { completion in
|
||||
completion(expected, nil)
|
||||
return nil
|
||||
}
|
||||
|
||||
let loaded = try await FeaturePhotoLibraryItem(provider: provider).loadData()
|
||||
|
||||
#expect(loaded == expected)
|
||||
}
|
||||
|
||||
@Test
|
||||
func photoLibraryItemRejectsProvidersWithoutAnImage() async {
|
||||
let provider = NSItemProvider(
|
||||
item: "not an image" as NSString,
|
||||
typeIdentifier: UTType.plainText.identifier
|
||||
)
|
||||
|
||||
do {
|
||||
_ = try await FeaturePhotoLibraryItem(provider: provider).loadData()
|
||||
Issue.record("Expected a non-image provider to be rejected")
|
||||
} catch FeatureImageAttachmentError.invalidImage {
|
||||
// Expected.
|
||||
} catch {
|
||||
Issue.record("Unexpected error: \(error)")
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user