Repository Public
1// SP Notes iOS2// File: Features/Attachments/MediaPickers.swift3// Description: SwiftUI wrappers of the system pickers that bring a file into a note: photo library (no permission prompt), camera,4// Files importer. Each one hands back temporary file URLs that keep the original file names.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import PhotosUI9import SwiftUI10import UIKit11import UniformTypeIdentifiers1213/// Temporary files of the pickers: one fresh directory per file so the original name is kept without collisions.14enum MediaTemp {15 static var root: URL { FileManager.default.temporaryDirectory.appendingPathComponent("spn-media", isDirectory: true) }1617 /// A URL in a fresh directory for a file with this name (the name is sanitized; the directory exists).18 static func newFileURL(named name: String) throws -> URL {19 let directory = root.appendingPathComponent(UUID().uuidString, isDirectory: true)20 try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)21 return directory.appendingPathComponent(AttachmentFiles.safeName(name))22 }2324 /// Copies a file (security-scoped or not) into the temporary area and returns the copy.25 static func copy(_ source: URL, named name: String? = nil) throws -> URL {26 let scoped = source.startAccessingSecurityScopedResource()27 defer { if scoped { source.stopAccessingSecurityScopedResource() } }28 let destination = try newFileURL(named: name ?? source.lastPathComponent)29 var coordinationError: NSError?30 var copyError: Error?31 // Coordinated read: files of a cloud provider are downloaded before the copy.32 NSFileCoordinator().coordinate(readingItemAt: source, options: [], error: &coordinationError) { url in33 do { try FileManager.default.copyItem(at: url, to: destination) } catch { copyError = error }34 }35 if let error = coordinationError ?? copyError { throw error }36 return destination37 }3839 static func write(_ data: Data, named name: String) throws -> URL {40 let destination = try newFileURL(named: name)41 try data.write(to: destination, options: .atomic)42 return destination43 }4445 /// Removes a temporary file and its directory once the caller has imported it.46 static func discard(_ url: URL) {47 let directory = url.deletingLastPathComponent()48 guard directory.deletingLastPathComponent().standardizedFileURL == root.standardizedFileURL else { return }49 try? FileManager.default.removeItem(at: directory)50 }5152 /// Removes everything left behind (call at launch).53 static func purge() { try? FileManager.default.removeItem(at: root) }54}5556// MARK: - Photo library5758/// The system photo picker (out of process: no photo-library permission is needed). Images only.59/// `onPick` receives the temporary files in the order of the selection; an empty array means the user cancelled.60struct PhotoLibraryPicker: UIViewControllerRepresentable {61 /// 0 = no limit.62 var selectionLimit = 063 var onPick: @MainActor ([URL]) -> Void6465 func makeCoordinator() -> Coordinator { Coordinator(onPick: onPick) }6667 func makeUIViewController(context: Context) -> PHPickerViewController {68 var configuration = PHPickerConfiguration()69 configuration.filter = .images70 configuration.selectionLimit = selectionLimit71 configuration.selection = selectionLimit == 1 ? .default : .ordered72 configuration.preferredAssetRepresentationMode = .compatible // HEIC is transcoded to JPEG when needed, so every device can read it73 let picker = PHPickerViewController(configuration: configuration)74 picker.delegate = context.coordinator75 picker.view.accessibilityIdentifier = "photo-library-picker"76 return picker77 }7879 func updateUIViewController(_ controller: PHPickerViewController, context: Context) { context.coordinator.onPick = onPick }8081 @MainActor82 final class Coordinator: NSObject, PHPickerViewControllerDelegate {83 var onPick: @MainActor ([URL]) -> Void84 init(onPick: @escaping @MainActor ([URL]) -> Void) { self.onPick = onPick }8586 func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {87 let providers = results.map(\.itemProvider)88 guard !providers.isEmpty else { onPick([]); return }89 Task { @MainActor in90 var urls: [URL] = []91 for (index, provider) in providers.enumerated() {92 if let url = await Self.loadImageFile(from: provider, fallbackName: "photo-\(index + 1)") { urls.append(url) }93 }94 onPick(urls)95 }96 }9798 /// Copies the picked image to a temporary file named after the original (`suggestedName` has no extension).99 private static func loadImageFile(from provider: NSItemProvider, fallbackName: String) async -> URL? {100 let identifier = provider.registeredTypeIdentifiers.first { UTType($0)?.conforms(to: .image) == true } ?? UTType.image.identifier101 let suggested = provider.suggestedName102 return await withCheckedContinuation { (continuation: CheckedContinuation<URL?, Never>) in103 provider.loadFileRepresentation(forTypeIdentifier: identifier) { url, _ in104 // The file only exists during this callback: copy it now.105 guard let url else { continuation.resume(returning: nil); return }106 let ext = url.pathExtension.isEmpty ? (UTType(identifier)?.preferredFilenameExtension ?? "jpg") : url.pathExtension107 let base = (suggested?.isEmpty == false ? suggested! : fallbackName)108 let name = (base as NSString).pathExtension.lowercased() == ext.lowercased() ? base : "\(base).\(ext)"109 continuation.resume(returning: try? MediaTemp.copy(url, named: name))110 }111 }112 }113 }114}115116// MARK: - Camera117118/// Takes one photo with the camera and returns it as a JPEG temporary file. Check `isAvailable` first (false on the simulator).119struct CameraPicker: UIViewControllerRepresentable {120 static var isAvailable: Bool { UIImagePickerController.isSourceTypeAvailable(.camera) }121122 /// nil when the user cancelled or the picture could not be written.123 var onCapture: @MainActor (URL?) -> Void124125 func makeCoordinator() -> Coordinator { Coordinator(onCapture: onCapture) }126127 func makeUIViewController(context: Context) -> UIImagePickerController {128 let picker = UIImagePickerController()129 picker.sourceType = Self.isAvailable ? .camera : .photoLibrary130 picker.mediaTypes = [UTType.image.identifier]131 picker.delegate = context.coordinator132 return picker133 }134135 func updateUIViewController(_ controller: UIImagePickerController, context: Context) { context.coordinator.onCapture = onCapture }136137 @MainActor138 final class Coordinator: NSObject, UIImagePickerControllerDelegate, UINavigationControllerDelegate {139 var onCapture: @MainActor (URL?) -> Void140 init(onCapture: @escaping @MainActor (URL?) -> Void) { self.onCapture = onCapture }141142 func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any]) {143 let image = info[.originalImage] as? UIImage144 let name = "Photo \(Self.stamp()).jpg"145 let url = image?.jpegData(compressionQuality: 0.9).flatMap { try? MediaTemp.write($0, named: name) }146 onCapture(url)147 }148149 func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { onCapture(nil) }150151 static func stamp() -> String {152 let formatter = DateFormatter()153 formatter.locale = Locale(identifier: "en_US_POSIX")154 formatter.dateFormat = "yyyy-MM-dd HH.mm.ss"155 return formatter.string(from: Date())156 }157 }158}159160// MARK: - Files161162extension View {163 /// The Files importer for attachments: any kind of file, several at once. The picked (security-scoped) files are copied to164 /// temporary files before `onPick` is called; the files that could not be read are counted in `failed`.165 func attachmentFileImporter(isPresented: Binding<Bool>, allowedTypes: [UTType] = [.item], onPick: @escaping @MainActor (_ files: [URL], _ failed: Int) -> Void) -> some View {166 fileImporter(isPresented: isPresented, allowedContentTypes: allowedTypes, allowsMultipleSelection: true) { result in167 guard case .success(let urls) = result, !urls.isEmpty else { return }168 Task.detached(priority: .userInitiated) {169 var copies: [URL] = []170 var failed = 0171 for url in urls {172 if let copy = try? MediaTemp.copy(url) { copies.append(copy) } else { failed += 1 }173 }174 let files = copies, failures = failed175 await MainActor.run { onPick(files, failures) }176 }177 }178 }179}180