Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ImageAttachmentViews.swift

808 lines29.3 KB

1import ImageIO
2import PhotosUI
3import SwiftUI
4import UniformTypeIdentifiers
5import UIKit
6​
7enum FeatureImageAttachmentLimits {
8 /// Shared by every attachment entry point (picker, camera, files, and
9 /// paste), so their in-flight reservations count against the same cap.
10 static let maximumCount = 8
12​
13struct FeatureAttachmentPreparationState: Equatable {
14 struct Operation: Hashable {
15 fileprivate let id: UUID
16 }
17​
18 private var pendingItemsByOperation: [Operation: Int] = [:]
19​
20 var isPreparing: Bool {
21 !pendingItemsByOperation.isEmpty
22 }
23​
24 var pendingItemCount: Int {
25 pendingItemsByOperation.values.reduce(0, +)
26 }
27​
28 var statusLabel: String {
29 pendingItemCount == 1
30 ? "Preparing attachment…"
31 : "Preparing \(pendingItemCount) attachments…"
32 }
33​
34 @discardableResult
35 mutating func begin(itemCount: Int, id: UUID = UUID()) -> Operation {
36 let operation = Operation(id: id)
37 pendingItemsByOperation[operation] = max(1, itemCount)
38 return operation
39 }
40​
41 mutating func finish(_ operation: Operation) {
42 pendingItemsByOperation.removeValue(forKey: operation)
43 }
45​
46struct FeatureAttachmentOperationIdentity: Equatable {
47 let ownerID: String
48 let environmentID: String?
49 let generation: UUID
50​
51 func matches(ownerID: String, environmentID: String?, generation: UUID) -> Bool {
52 self.ownerID == ownerID
53 && self.environmentID == environmentID
54 && self.generation == generation
55 }
57​
58struct FeatureImageAttachmentPicker: View {
59 private enum Source {
60 case photoLibrary
61 case camera
62 case files
63 }
64​
65 @Binding var attachments: [FeatureDraftAttachment]
66 @Binding var preparationState: FeatureAttachmentPreparationState
67 @Binding var isFlowActive: Bool
68 let maximumCount: Int
69 let draftOwnerID: String
70 let environmentID: String?
71 let imagesAllowed: Bool
72 let maximumFileBytes: Int?
73​
74 @State private var isAttachmentSourcePresented = false
75 @State private var isPhotoLibraryPresented = false
76 @State private var pendingPhotoLibraryItems: [FeaturePhotoLibraryItem] = []
77 @State private var isCameraPresented = false
78 @State private var isFileImporterPresented = false
79 @State private var sourcePresentationTask: Task<Void, Never>?
80 @State private var errorMessage: String?
81 @State private var generation = UUID()
82 @State private var flowIdentity: FeatureAttachmentOperationIdentity?
83​
84 init(
85 attachments: Binding<[FeatureDraftAttachment]>,
86 preparationState: Binding<FeatureAttachmentPreparationState>,
87 isFlowActive: Binding<Bool>,
88 draftOwnerID: String,
89 environmentID: String?,
90 imagesAllowed: Bool,
91 maximumFileBytes: Int?,
92 maximumCount: Int = FeatureImageAttachmentLimits.maximumCount
93 ) {
94 _attachments = attachments
95 _preparationState = preparationState
96 _isFlowActive = isFlowActive
97 self.maximumCount = maximumCount
98 self.draftOwnerID = draftOwnerID
99 self.environmentID = environmentID
100 self.imagesAllowed = imagesAllowed
101 self.maximumFileBytes = maximumFileBytes
102 }
103​
104 var body: some View {
105 Button {
106 flowIdentity = FeatureAttachmentOperationIdentity(
107 ownerID: draftOwnerID,
108 environmentID: environmentID,
109 generation: generation
110 )
111 isFlowActive = true
112 isAttachmentSourcePresented = true
113 } label: {
114 Image(systemName: preparationState.isPreparing ? "hourglass" : "paperclip")
115 .font(.system(size: 17, weight: .medium))
116 .foregroundStyle(T3Colors.textSecondary)
117 .frame(width: T3Metrics.minimumTapTarget, height: T3Metrics.minimumTapTarget)
118 .contentShape(Rectangle())
119 }
120 .buttonStyle(.plain)
121 .disabled(!canAdd)
122 .opacity(canAdd ? 1 : 0.3)
123 .accessibilityLabel(attachmentAccessibilityLabel)
124 .accessibilityIdentifier("image-attachment-picker")
125 .accessibilityHint(attachmentAccessibilityHint)
126 .confirmationDialog("Add attachment", isPresented: $isAttachmentSourcePresented) {
127 Button("Photo Library") { present(.photoLibrary) }
128 .disabled(!imagesAllowed && maximumFileBytes == nil)
129 Button("Camera") { present(.camera) }
130 .disabled(!imagesAllowed || !UIImagePickerController.isSourceTypeAvailable(.camera))
131 Button("Files") { present(.files) }
132 Button("Cancel", role: .cancel) {
133 isFlowActive = false
134 }
135 }
136 .fullScreenCover(
137 isPresented: $isPhotoLibraryPresented,
138 onDismiss: finishPhotoLibrarySelection
139 ) {
140 FeaturePhotoLibraryPicker(
141 maximumCount: max(1, remainingCount),
142 imagesAllowed: imagesAllowed,
143 videosAllowed: maximumFileBytes != nil,
144 onFinish: { items in
145 pendingPhotoLibraryItems = items
146 isPhotoLibraryPresented = false
147 }
148 )
149 .ignoresSafeArea()
150 }
151 .fullScreenCover(isPresented: $isCameraPresented) {
152 FeatureCameraPicker(
153 onCapture: loadCapturedImage,
154 onCancel: {
155 isCameraPresented = false
156 isFlowActive = false
157 }
158 )
159 .ignoresSafeArea()
160 }
161 .fileImporter(
162 isPresented: $isFileImporterPresented,
163 allowedContentTypes: maximumFileBytes == nil ? [.image] : [.item],
164 allowsMultipleSelection: true,
165 onCompletion: loadFiles
166 )
167 .alert(
168 "Couldn’t add attachment",
169 isPresented: Binding(
170 get: { errorMessage != nil },
171 set: { if !$0 { errorMessage = nil } }
172 )
173 ) {
174 Button("OK") { errorMessage = nil }
175 } message: {
176 Text(errorMessage ?? "")
177 }
178 .onDisappear {
179 sourcePresentationTask?.cancel()
180 if !isFlowActive {
181 generation = UUID()
182 flowIdentity = nil
183 }
184 }
185 .onChange(of: draftOwnerID) {
186 generation = UUID()
187 flowIdentity = nil
188 pendingPhotoLibraryItems = []
189 }
190 .onChange(of: environmentID) {
191 generation = UUID()
192 flowIdentity = nil
193 pendingPhotoLibraryItems = []
194 }
195 }
196​
197 private var remainingCount: Int {
198 max(0, maximumCount - attachments.count)
199 }
200​
201 private var canAdd: Bool {
202 (imagesAllowed || maximumFileBytes != nil)
203 && !preparationState.isPreparing && remainingCount > 0
204 }
205​
206 private var attachmentAccessibilityLabel: String {
207 if preparationState.isPreparing { return preparationState.statusLabel }
208 if remainingCount == 0 { return "Attachment limit reached" }
209 return "Add attachment"
210 }
211​
212 private var attachmentAccessibilityHint: String {
213 if !imagesAllowed && maximumFileBytes == nil { return "Attachments are not supported" }
214 if remainingCount == 0 { return "Remove an attachment before adding another" }
215 return maximumFileBytes == nil
216 ? "Choose a photo, take a photo, or browse image files"
217 : "Choose a photo, video, or file"
218 }
219​
220 private func present(_ source: Source) {
221 sourcePresentationTask?.cancel()
222 isAttachmentSourcePresented = false
223 sourcePresentationTask = Task { @MainActor in
224 // A confirmation dialog is still the active presenter while its action
225 // runs. Wait for its dismissal animation before presenting another
226 // controller or UIKit can reject (or race) the new presentation.
227 try? await Task.sleep(for: .milliseconds(300))
228 guard !Task.isCancelled, canAdd else {
229 isFlowActive = false
230 return
231 }
232 switch source {
233 case .photoLibrary:
234 isPhotoLibraryPresented = true
235 case .camera:
236 isCameraPresented = true
237 case .files:
238 isFileImporterPresented = true
239 }
240 }
241 }
242​
243 private func finishPhotoLibrarySelection() {
244 guard let identity = flowIdentity else {
245 pendingPhotoLibraryItems = []
246 isFlowActive = false
247 return
248 }
249 Task { @MainActor in
250 // Keep PhotosUI presentation and asset materialization in separate turns.
251 // Some OS versions become stuck or dismiss mid-selection when the picker
252 // and its selection are driven by the same SwiftUI binding transaction.
253 await Task.yield()
254 guard !isPhotoLibraryPresented, !pendingPhotoLibraryItems.isEmpty, canAdd else {
255 pendingPhotoLibraryItems = []
256 isFlowActive = false
257 return
258 }
259​
260 let selected = Array(pendingPhotoLibraryItems.prefix(remainingCount))
261 pendingPhotoLibraryItems = []
262 let firstOrdinal = attachments.count + preparationState.pendingItemCount + 1
263 let operation = preparationState.begin(itemCount: selected.count)
264​
265 defer {
266 preparationState.finish(operation)
267 isFlowActive = false
268 }
269​
270 for (offset, item) in selected.enumerated() {
271 do {
272 let attachment = try await item.loadAttachment(
273 ordinal: firstOrdinal + offset,
274 maximumFileBytes: maximumFileBytes
275 )
276 guard identity.matches(
277 ownerID: draftOwnerID,
278 environmentID: environmentID,
279 generation: generation
280 ) else {
281 discardOwnedFile(for: attachment)
282 return
283 }
284 if attachment.mimeType.hasPrefix("image/"), !imagesAllowed {
285 throw FeatureAttachmentIntakeError.imagesUnsupported
286 }
287 attachments.append(attachment)
288 } catch {
289 errorMessage = error.localizedDescription
290 }
291 }
292 }
293 }
294​
295 private func loadCapturedImage(_ image: UIImage) {
296 isCameraPresented = false
297 guard canAdd else {
298 isFlowActive = false
299 return
300 }
301 guard let identity = flowIdentity else {
302 isFlowActive = false
303 return
304 }
305 let operation = preparationState.begin(itemCount: 1)
306​
307 Task {
308 defer {
309 preparationState.finish(operation)
310 isFlowActive = false
311 }
312 do {
313 let ordinal = attachments.count + 1
314 let data = try await Task.detached(priority: .userInitiated) {
315 guard let data = image.jpegData(compressionQuality: 0.94) else {
316 throw FeatureImageAttachmentError.encodingFailed
317 }
318 return data
319 }.value
320 let attachment = try await Task.detached(priority: .userInitiated) {
321 try FeatureImageProcessor.attachment(from: data, ordinal: ordinal)
322 }.value
323 guard identity.matches(
324 ownerID: draftOwnerID,
325 environmentID: environmentID,
326 generation: generation
327 ) else { return }
328 attachments.append(attachment)
329 } catch {
330 errorMessage = error.localizedDescription
331 }
332 }
333 }
334​
335 private func loadFiles(_ result: Result<[URL], Error>) {
336 switch result {
337 case .failure(let error):
338 errorMessage = error.localizedDescription
339 isFlowActive = false
340 case .success(let urls):
341 guard !urls.isEmpty, canAdd, let identity = flowIdentity else {
342 isFlowActive = false
343 return
344 }
345 let operation = preparationState.begin(itemCount: min(urls.count, remainingCount))
346​
347 Task {
348 defer {
349 preparationState.finish(operation)
350 isFlowActive = false
351 }
352 for url in urls.prefix(remainingCount) {
353 do {
354 let attachment = try await prepareFile(url)
355 guard identity.matches(
356 ownerID: draftOwnerID,
357 environmentID: environmentID,
358 generation: generation
359 ) else {
360 discardOwnedFile(for: attachment)
361 return
362 }
363 attachments.append(attachment)
364 } catch {
365 errorMessage = error.localizedDescription
366 break
367 }
368 }
369 }
370 }
371 }
372​
373 private func prepareFile(_ url: URL) async throws -> FeatureDraftAttachment {
374 let type = UTType(filenameExtension: url.pathExtension)
375 if type?.conforms(to: .image) == true {
376 guard imagesAllowed else { throw FeatureAttachmentIntakeError.imagesUnsupported }
377 let ordinal = attachments.count + 1
378 let data = try await Task.detached(priority: .userInitiated) {
379 let hasAccess = url.startAccessingSecurityScopedResource()
380 defer { if hasAccess { url.stopAccessingSecurityScopedResource() } }
381 return try Data(contentsOf: url, options: .mappedIfSafe)
382 }.value
383 return try await Task.detached(priority: .userInitiated) {
384 try FeatureImageProcessor.attachment(from: data, ordinal: ordinal)
385 }.value
386 }
387 guard let maximumFileBytes else { throw FeatureAttachmentIntakeError.filesUnsupported }
388 let id = UUID()
389 let owned = try await Task.detached(priority: .userInitiated) {
390 try ManagedAttachmentFileStore().copyOwnedFile(
391 from: url,
392 attachmentID: id,
393 originalFileName: url.lastPathComponent,
394 maximumBytes: maximumFileBytes
395 )
396 }.value
397 return FeatureDraftAttachment(
398 id: id,
399 ownedFile: owned,
400 filename: url.lastPathComponent,
401 mimeType: type?.preferredMIMEType ?? "application/octet-stream"
402 )
403 }
404​
405 private func appendImage(_ data: Data, ordinal: Int? = nil) async throws {
406 let ordinal = ordinal ?? attachments.count + 1
407 let attachment = try await Task.detached(priority: .userInitiated) {
408 try FeatureImageProcessor.attachment(from: data, ordinal: ordinal)
409 }.value
410 attachments.append(attachment)
411 }
412​
413 private func discardOwnedFile(for attachment: FeatureDraftAttachment) {
414 guard let fileName = attachment.ownedFile?.fileName else { return }
415 try? ManagedAttachmentFileStore().removeOwnedFile(fileName: fileName)
416 }
418​
419private struct FeaturePhotoLibraryItem: @unchecked Sendable {
420 let provider: NSItemProvider
421​
422 @MainActor
423 func loadAttachment(
424 ordinal: Int,
425 maximumFileBytes: Int?
426 ) async throws -> FeatureDraftAttachment {
427 if provider.registeredTypeIdentifiers.contains(where: {
428 UTType($0)?.conforms(to: .image) == true
429 }) {
430 let data = try await FeatureImageItemProviderLoader.data(from: provider)
431 return try await Task.detached(priority: .userInitiated) {
432 try FeatureImageProcessor.attachment(from: data, ordinal: ordinal)
433 }.value
434 }
435 guard let maximumFileBytes else { throw FeatureAttachmentIntakeError.filesUnsupported }
436 return try await FeatureFileItemProviderLoader.attachment(
437 from: provider,
438 maximumBytes: maximumFileBytes
439 )
440 }
442​
443enum FeatureFileItemProviderLoader {
444 @MainActor
445 static func attachment(
446 from provider: NSItemProvider,
447 maximumBytes: Int
448 ) async throws -> FeatureDraftAttachment {
449 guard let identifier = provider.registeredTypeIdentifiers.first(where: {
450 UTType($0)?.conforms(to: .movie) == true
451 || UTType($0)?.conforms(to: .item) == true
452 }) else { throw FeatureAttachmentIntakeError.invalidFile }
453 let type = UTType(identifier)
454 let id = UUID()
455 let preferredExtension = type?.preferredFilenameExtension
456 let suggestedName = provider.suggestedName ?? "Attachment"
457 let suggestedURL = URL(fileURLWithPath: suggestedName)
458 let fileName = suggestedURL.pathExtension.isEmpty
459 ? preferredExtension.map { "\(suggestedName).\($0)" } ?? suggestedName
460 : suggestedName
461​
462 return try await withCheckedThrowingContinuation { continuation in
463 provider.loadFileRepresentation(forTypeIdentifier: identifier) { url, error in
464 do {
465 guard let url else {
466 throw error ?? FeatureAttachmentIntakeError.invalidFile
467 }
468 // The provider deletes this URL when the callback returns.
469 let owned = try ManagedAttachmentFileStore().copyOwnedFile(
470 from: url,
471 attachmentID: id,
472 originalFileName: fileName,
473 maximumBytes: maximumBytes
474 )
475 continuation.resume(returning: FeatureDraftAttachment(
476 id: id,
477 ownedFile: owned,
478 filename: fileName,
479 mimeType: type?.preferredMIMEType ?? "application/octet-stream"
480 ))
481 } catch {
482 continuation.resume(throwing: error)
483 }
484 }
485 }
486 }
488​
489/// Loads raw image bytes from an `NSItemProvider`, shared by the photo
490/// library picker and the composer's paste path. Main-actor isolated because
491/// providers arrive from main-actor UI callbacks and are not `Sendable`; the
492/// provider does its own work off-thread.
493enum FeatureImageItemProviderLoader {
494 struct Load {
495 fileprivate let values: AsyncThrowingStream<Data, Error>
496​
497 @MainActor
498 func data() async throws -> Data {
499 for try await data in values {
500 return data
501 }
502 throw FeatureImageAttachmentError.encodingFailed
503 }
504 }
505​
506 /// Starts the provider request before returning. Drop callers use this
507 /// form so access begins within `performDrop`, while the provider grant is
508 /// active.
509 @MainActor
510 static func start(from provider: NSItemProvider) throws -> Load {
511 guard let typeIdentifier = provider.registeredTypeIdentifiers.first(where: { identifier in
512 UTType(identifier)?.conforms(to: .image) == true
513 }) else {
514 throw FeatureImageAttachmentError.invalidImage
515 }
516​
517 let values = AsyncThrowingStream<Data, Error> { continuation in
518 provider.loadDataRepresentation(forTypeIdentifier: typeIdentifier) { data, error in
519 if let data {
520 continuation.yield(data)
521 continuation.finish()
522 } else {
523 continuation.finish(
524 throwing: error ?? FeatureImageAttachmentError.encodingFailed
525 )
526 }
527 }
528 }
529 return Load(values: values)
530 }
531​
532 @MainActor
533 static func data(from provider: NSItemProvider) async throws -> Data {
534 try await start(from: provider).data()
535 }
537​
538private struct FeaturePhotoLibraryPicker: UIViewControllerRepresentable {
539 let maximumCount: Int
540 let imagesAllowed: Bool
541 let videosAllowed: Bool
542 let onFinish: @MainActor ([FeaturePhotoLibraryItem]) -> Void
543​
544 func makeCoordinator() -> Coordinator {
545 Coordinator(onFinish: onFinish)
546 }
547​
548 func makeUIViewController(context: Context) -> PHPickerViewController {
549 var configuration = PHPickerConfiguration()
550 configuration.filter = if imagesAllowed && videosAllowed {
551 .any(of: [.images, .videos])
552 } else if videosAllowed {
553 .videos
554 } else {
555 .images
556 }
557 configuration.selectionLimit = maximumCount
558 configuration.selection = .ordered
559 configuration.preferredAssetRepresentationMode = .compatible
560​
561 let picker = PHPickerViewController(configuration: configuration)
562 picker.delegate = context.coordinator
563 return picker
564 }
565​
566 func updateUIViewController(_ picker: PHPickerViewController, context: Context) {}
567​
568 final class Coordinator: NSObject, PHPickerViewControllerDelegate {
569 private let onFinish: @MainActor ([FeaturePhotoLibraryItem]) -> Void
570 private var didFinish = false
571​
572 init(onFinish: @escaping @MainActor ([FeaturePhotoLibraryItem]) -> Void) {
573 self.onFinish = onFinish
574 }
575​
576 func picker(_: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {
577 guard !didFinish else { return }
578 didFinish = true
579​
580 let items = results.map { FeaturePhotoLibraryItem(provider: $0.itemProvider) }
581 Task { @MainActor in
582 onFinish(items)
583 }
584 }
585 }
587​
588struct FeatureAttachmentStrip: View {
589 @Binding var attachments: [FeatureDraftAttachment]
590​
591 var body: some View {
592 if !attachments.isEmpty {
593 ScrollView(.horizontal) {
594 HStack(spacing: 8) {
595 ForEach(attachments) { attachment in
596 FeatureAttachmentThumbnail(attachment: attachment) {
597 attachments.removeAll { $0.id == attachment.id }
598 }
599 }
600 }
601 .padding(.horizontal, 1)
602 }
603 .scrollIndicators(.hidden)
604 .accessibilityLabel("\(attachments.count) attachments")
605 }
606 }
608​
609private struct FeatureAttachmentThumbnail: View {
610 let attachment: FeatureDraftAttachment
611 let onRemove: () -> Void
612 @State private var image: UIImage?
613​
614 var body: some View {
615 ZStack(alignment: .topTrailing) {
616 Group {
617 if let image {
618 Image(uiImage: image)
619 .resizable()
620 .scaledToFill()
621 } else if attachment.mimeType.hasPrefix("image/") {
622 Image(systemName: "photo")
623 .foregroundStyle(T3Colors.textSecondary)
624 } else {
625 VStack(spacing: 3) {
626 Image(systemName: "doc")
627 Text(attachment.filename)
628 .font(.caption2)
629 .lineLimit(1)
630 Text(ByteCountFormatter.string(
631 fromByteCount: Int64(attachment.byteCount),
632 countStyle: .file
633 ))
634 .font(.caption2)
635 }
636 .foregroundStyle(T3Colors.textSecondary)
637 }
638 }
639 .frame(width: 58, height: 58)
640 .background(T3Colors.surface)
641 .clipShape(RoundedRectangle(cornerRadius: 10, style: .continuous))
642​
643 Button(action: onRemove) {
644 Image(systemName: "xmark")
645 .font(.system(size: 9, weight: .bold))
646 .foregroundStyle(.white)
647 .frame(width: 22, height: 22)
648 .background(.black.opacity(0.78), in: Circle())
649 .frame(
650 width: T3Metrics.minimumTapTarget,
651 height: T3Metrics.minimumTapTarget
652 )
653 .contentShape(Rectangle())
654 }
655 .offset(x: 11, y: -11)
656 .accessibilityLabel("Remove \(attachment.filename)")
657 }
658 .padding(.top, 11)
659 .padding(.trailing, 11)
660 .task(id: attachment.id) {
661 guard attachment.mimeType.hasPrefix("image/") else { return }
662 let data = attachment.thumbnailData ?? attachment.data
663 image = await Task.detached(priority: .utility) {
664 UIImage(data: data)
665 }.value
666 }
667 }
669​
670private struct FeatureCameraPicker: UIViewControllerRepresentable {
671 let onCapture: (UIImage) -> Void
672 let onCancel: () -> Void
673​
674 func makeCoordinator() -> Coordinator {
675 Coordinator(onCapture: onCapture, onCancel: onCancel)
676 }
677​
678 func makeUIViewController(context: Context) -> UIImagePickerController {
679 let controller = UIImagePickerController()
680 controller.sourceType = .camera
681 controller.cameraCaptureMode = .photo
682 controller.delegate = context.coordinator
683 return controller
684 }
685​
686 func updateUIViewController(_ controller: UIImagePickerController, context: Context) {}
687​
688 final class Coordinator: NSObject, UINavigationControllerDelegate, UIImagePickerControllerDelegate {
689 private let onCapture: (UIImage) -> Void
690 private let onCancel: () -> Void
691​
692 init(onCapture: @escaping (UIImage) -> Void, onCancel: @escaping () -> Void) {
693 self.onCapture = onCapture
694 self.onCancel = onCancel
695 }
696​
697 func imagePickerController(
698 _ picker: UIImagePickerController,
699 didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any]
700 ) {
701 guard let image = info[.originalImage] as? UIImage else {
702 onCancel()
703 return
704 }
705 onCapture(image)
706 }
707​
708 func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
709 onCancel()
710 }
711 }
713​
714enum FeatureImageProcessor {
715 private static let maximumDimension: CGFloat = 2_048
716 private static let maximumEncodedBytes = 10 * 1_024 * 1_024
717​
718 static func thumbnail(fileURL: URL) -> Data? {
719 guard let source = CGImageSourceCreateWithURL(fileURL as CFURL, nil),
720 let image = CGImageSourceCreateThumbnailAtIndex(source, 0, [
721 kCGImageSourceCreateThumbnailFromImageAlways: true,
722 kCGImageSourceCreateThumbnailWithTransform: true,
723 kCGImageSourceThumbnailMaxPixelSize: 160,
724 ] as CFDictionary) else { return nil }
725 return UIImage(cgImage: image).jpegData(compressionQuality: 0.72)
726 }
727​
728 static func attachment(
729 from sourceData: Data,
730 ordinal: Int
731 ) throws -> FeatureDraftAttachment {
732 guard let source = CGImageSourceCreateWithData(sourceData as CFData, nil),
733 let image = CGImageSourceCreateThumbnailAtIndex(
734 source,
735 0,
736 [
737 kCGImageSourceCreateThumbnailFromImageAlways: true,
738 kCGImageSourceCreateThumbnailWithTransform: true,
739 kCGImageSourceThumbnailMaxPixelSize: maximumDimension,
740 kCGImageSourceShouldCacheImmediately: true,
741 ] as CFDictionary
742 ) else {
743 throw FeatureImageAttachmentError.invalidImage
744 }
745​
746 let preparedImage = UIImage(cgImage: image)
747 guard let data = preparedImage.jpegData(compressionQuality: 0.82),
748 let thumbnailData = thumbnail(from: preparedImage) else {
749 throw FeatureImageAttachmentError.encodingFailed
750 }
751 guard data.count <= maximumEncodedBytes else {
752 throw FeatureImageAttachmentError.tooLarge
753 }
754​
755 return FeatureDraftAttachment(
756 data: data,
757 thumbnailData: thumbnailData,
758 filename: "Image \(ordinal).jpg",
759 mimeType: "image/jpeg"
760 )
761 }
762​
763 private static func thumbnail(from image: UIImage) -> Data? {
764 let longestSide = max(image.size.width, image.size.height)
765 let scale = min(1, 160 / longestSide)
766 let size = CGSize(
767 width: max(1, image.size.width * scale),
768 height: max(1, image.size.height * scale)
769 )
770 let format = UIGraphicsImageRendererFormat()
771 format.scale = 1
772 let renderer = UIGraphicsImageRenderer(size: size, format: format)
773 return renderer.image { _ in
774 image.draw(in: CGRect(origin: .zero, size: size))
775 }.jpegData(compressionQuality: 0.72)
776 }
778​
779enum FeatureImageAttachmentError: LocalizedError {
780 case invalidImage
781 case encodingFailed
782 case tooLarge
783​
784 var errorDescription: String? {
785 switch self {
786 case .invalidImage:
787 "That photo could not be read."
788 case .encodingFailed:
789 "That photo could not be prepared."
790 case .tooLarge:
791 "Images must be smaller than 10 MB."
792 }
793 }
795​
796enum FeatureAttachmentIntakeError: LocalizedError {
797 case invalidFile
798 case filesUnsupported
799 case imagesUnsupported
800​
801 var errorDescription: String? {
802 switch self {
803 case .invalidFile: "That file could not be read."
804 case .filesUnsupported: "This environment does not accept file attachments."
805 case .imagesUnsupported: "The selected model does not accept images."
806 }
807 }