iOS: chooseFromGallery asks for photo library access before the user picks anything
Nadie ha tomado este issue todavía.
Evaluación
- Dificultad
- 4/5
- Tiempo estimado
- 3-5 días
- Aptitud para principiantes
- 45/100
Línea de trabajo
Start in CameraPlugin.swift at chooseFromGallery, then follow IONCAMRFlowBehaviour.chooseFromGallery to IONCAMRPermissionsBehaviour.checkForPhotoLibrary, which triggers PHPhotoLibrary.requestAuthorization before IONCAMRGalleryBehaviour.displayPhotoLibraryView opens. Reproduce on the iOS simulator with xcrun simctl privacy <udid> reset all <bundle id> and confirm the prompt appears. Done means a photo-only pick opens PHPickerViewController with no Photos prompt, while video and edit keep their current flow; the proposed patch in the issue is a starting point, and the scope choice needs maintainer input.
Escrito por el modelo de indexación a partir del texto del issue.
Descripción
Plugin version: 8.2.6 (ion-ios-camera 2.0.0), iOS 15+. Related to #74, which covers the picker UI. This issue is about the permission prompt.
What happens. chooseFromGallery on iOS asks the user for photo library access before anything opens. When the user taps "Limit Access" or "Don't Allow", the app gets a partial library or an error, although the user only wanted to pick one photo.
Call order (ion-ios-camera 2.0.0):
CameraPlugin.chooseFromGallerycallsgalleryManager.chooseFromGallery(with:).IONCAMRFlowBehaviour.chooseFromGallerycallspermissionsBehaviour.checkForPhotoLibrary.IONCAMRPermissionsBehaviour.checkForPhotoLibrarycallsPHPhotoLibrary.requestAuthorization(for: .readWrite), which shows the system prompt the first time.- Only then
IONCAMRGalleryBehaviour.displayPhotoLibraryViewpresents the customIONCAMRPhotoLibraryView, built onPHAsset.fetchAssets. That grid really does need the authorization.
No option and no Info.plist key avoids step 3. The app has to declare NSPhotoLibraryUsageDescription and the user has to grant library access to pick a photo.
Why this matters. Since iOS 14, PHPickerViewController runs out of process and needs no photo library authorization. The app receives only the items the user picks. Apple's guidance is to use the system picker when an app only needs the photos the user selects, and to ask for library access only when the app needs the library itself. Before 8.1, getPhoto with CameraSource.Photos and pickImages presented PHPickerViewController, and the plugin still has that code (presentPhotoPicker). The authorization request in those older paths (showPhotos) was not needed either.
Minimal repro
- Fresh install, or reset privacy:
xcrun simctl privacy <udid> reset all <bundle id>. - Call
Camera.chooseFromGallery({ mediaType: MediaTypeSelection.Photo, allowMultipleSelection: false }). - Expected: the system photo picker opens with no prompt. Actual: "Allow access to your photos?" (Limit Access / Allow Full Access / Don't Allow) appears first.
Suggested fix. For photo-only picks without an edit step, present PHPickerViewController. Build it with PHPickerConfiguration() and no photoLibrary, so no asset identifier comes back and nothing touches PhotoKit. Load each pick with itemProvider.loadFileRepresentation(forTypeIdentifier: UTType.image.identifier) and copy it to a temporary file. That keeps the photo's own EXIF, including capture time and location unless the user turns location off in the picker's options. Return it as a MediaResult. We carry this as a local patch to CameraPlugin.swift (under 100 lines), tested on the iOS simulator: no prompt, and the app gets no Photos authorization. The patch is below. Keeping the custom grid for video and for edit, as the patch does, is one option; using the system picker for those too would be another.
Local patch (patch-package, CameraPlugin.swift)
diff --git a/node_modules/@capacitor/camera/ios/Sources/CameraPlugin/CameraPlugin.swift b/node_modules/@capacitor/camera/ios/Sources/CameraPlugin/CameraPlugin.swift
index 968733e..aea7dba 100644
--- a/node_modules/@capacitor/camera/ios/Sources/CameraPlugin/CameraPlugin.swift
+++ b/node_modules/@capacitor/camera/ios/Sources/CameraPlugin/CameraPlugin.swift
@@ -35,6 +35,8 @@ public class CameraPlugin: CAPPlugin, CAPBridgedPlugin {
private lazy var videoManager = IONCAMRFactory.createVideoManagerWrapper(withDelegate: self, and: self.bridge?.viewController ?? UIViewController())
private var imageCounter = 0
+ // patch-package: PHPickerViewController holds its delegate weakly.
+ private var galleryPhotoPickerDelegate: GalleryPhotoPickerDelegate?
public override func load() {
NotificationCenter.default.addObserver(
@@ -85,10 +87,35 @@ public class CameraPlugin: CAPPlugin, CAPBridgedPlugin {
@objc func chooseFromGallery(_ call: CAPPluginCall) {
handleCall(call, error: .chooseMultimediaIssue) { (options: IONCAMRGalleryOptions) in
- self.galleryManager.chooseFromGallery(with: options)
+ // patch-package: photos without an edit step go through the system
+ // PHPickerViewController. It runs out of process and needs no photo
+ // library authorization, while IONCameraLib's own grid asks for full
+ // read-write access before it opens. Video and edit keep that flow.
+ if options.mediaType == .picture && !options.allowEdit {
+ self.presentGalleryPhotoPicker(options)
+ } else {
+ self.galleryManager.chooseFromGallery(with: options)
+ }
}
}
+ private func presentGalleryPhotoPicker(_ options: IONCAMRGalleryOptions) {
+ // No photoLibrary in the configuration: no asset identifiers, so
+ // nothing here touches PhotoKit and no authorization prompt shows.
+ var configuration = PHPickerConfiguration()
+ configuration.filter = .images
+ configuration.selectionLimit = options.allowMultipleSelection ? options.limit : 1
+ let picker = PHPickerViewController(configuration: configuration)
+ let delegate = GalleryPhotoPickerDelegate(
+ webPath: { [weak self] url in self?.resolveWebPath(from: url.absoluteString) },
+ fail: { [weak self] error in self?.sendError(error) },
+ finish: { [weak self] results in self?.call?.resolve(["results": results]) }
+ )
+ galleryPhotoPickerDelegate = delegate
+ picker.delegate = delegate
+ bridge?.viewController?.present(picker, animated: true, completion: nil)
+ }
+
@objc func editURIPhoto(_ call: CAPPluginCall) {
handleCall(call, error: .editPictureIssue) { (options: IONCAMRPhotoEditOptions) in
self.editManager.editPhoto(with: options)
@@ -735,3 +762,63 @@ extension CameraPlugin: IONCAMRCallbackDelegate {
return exif.isEmpty ? nil : exif
}
}
+
+// patch-package: the chooseFromGallery photo path. Each picked item is copied
+// as the file the picker hands over (its own bytes and metadata, the capture
+// time and the position included unless the user turns them off in the
+// picker), in pick order. A cancel rejects with chooseMultimediaCancel; an
+// item that cannot be read fails the whole call with chooseMultimediaIssue.
+final class GalleryPhotoPickerDelegate: NSObject, PHPickerViewControllerDelegate {
+ private let webPath: (URL) -> String?
+ private let fail: (IONCAMRError) -> Void
+ private let finish: ([[String: Any]]) -> Void
+
+ init(webPath: @escaping (URL) -> String?, fail: @escaping (IONCAMRError) -> Void, finish: @escaping ([[String: Any]]) -> Void) {
+ self.webPath = webPath
+ self.fail = fail
+ self.finish = finish
+ }
+
+ func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {
+ picker.dismiss(animated: true, completion: nil)
+ guard !results.isEmpty else {
+ fail(.chooseMultimediaCancel)
+ return
+ }
+ var copies = [URL?](repeating: nil, count: results.count)
+ let lock = NSLock()
+ let group = DispatchGroup()
+ for (index, result) in results.enumerated() {
+ group.enter()
+ result.itemProvider.loadFileRepresentation(forTypeIdentifier: UTType.image.identifier) { url, error in
+ defer { group.leave() }
+ guard let url else {
+ CAPLog.print("chooseFromGallery: item \(index) unreadable: \(String(describing: error))")
+ return
+ }
+ let copy = FileManager.default.temporaryDirectory
+ .appendingPathComponent(UUID().uuidString)
+ .appendingPathExtension(url.pathExtension.isEmpty ? "jpg" : url.pathExtension)
+ do {
+ try FileManager.default.copyItem(at: url, to: copy)
+ lock.lock()
+ copies[index] = copy
+ lock.unlock()
+ } catch {
+ CAPLog.print("chooseFromGallery: item \(index) copy failed: \(error)")
+ }
+ }
+ }
+ group.notify(queue: .main) { [self] in
+ var items: [[String: Any]] = []
+ for copy in copies {
+ guard let copy, let path = webPath(copy) else {
+ fail(.chooseMultimediaIssue)
+ return
+ }
+ items.append(["type": 0, "uri": copy.absoluteString, "webPath": path, "saved": false])
+ }
+ finish(items)
+ }
+ }
+}
- Lenguaje dominante
- TypeScript
- Estrellas
- 6
- Forks
- 4
- Merge medio
- 2 d 11 h
- PR fusionados (30 d)
- 6
Preparar el entorno
- Sin Dockerfile ni archivo de Docker Compose
- Sin plantilla de pull request
- Leer la guía de contribución
Primeros pasos
- Lee el issue completo y luego la guía de contribución del proyecto.
- Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
- Haz un fork del repositorio y trabaja en una rama.
- Abre un pull request que haga referencia al número del issue.
Más de ionic-team/capacitor-camera
-
bug(android): NullPointerException on ActivityResultLauncher.unregister() in LegacyCameraFlowAbierto
Dificultad 2/5 1-3 horas Aptitud para principiantes 88/100
ionic-team/capacitor-camera#75 · 1 reacción ·
-
[Bug]: Crash SecurityException: No persistable permission grants found in IONCAMROpenPhotoPickerActivityQuizá libre de nuevo Un pull request para esta issue se cerró sin fusionarse. Abierto
Dificultad 2/5 1-3 horas Aptitud para principiantes 76/100
ionic-team/capacitor-camera#58 · 1 comentario ·
-
Dificultad 3/5 1-2 días Aptitud para principiantes 67/100
-
Dificultad 3/5 1-2 días Aptitud para principiantes 68/100
-
Dificultad 3/5 1-2 días Aptitud para principiantes 68/100
ionic-team/capacitor-camera#76 · 1 comentario · 1 reacción ·
Todos los issues de ionic-team/capacitor-camera
Issues similares
-
community first-timers-only good first issue hacktoberfest help wanted low hanging fruit up-for-grabs
Dificultad 1/5 Menos de una hora Aptitud para principiantes 85/100
lingdojo/kana-dojo#34223 · 1 comentario · 5 reacciones ·
Los mantenedores suelen responder en 1 día
-
bug status: needs triage
Dificultad 2/5 1-3 horas Aptitud para principiantes 76/100
mastra-ai/mastra#30587 · 1 comentario ·
Los mantenedores suelen responder en 1 día
-
area:web p2 product:business triage:active type:bug
Dificultad 2/5 1-3 horas Aptitud para principiantes 76/100
cuadrao-ai/argus#2228 ·
Los mantenedores suelen responder en 1 día
-
Dificultad 2/5 1-3 horas Aptitud para principiantes 88/100
embedpdf/embed-pdf-viewer#1098 ·
Los mantenedores suelen responder en 1 día
-
.Needs Triage .Team/Metabot Priority:P3 Type:Bug
Dificultad 2/5 1-3 horas Aptitud para principiantes 73/100
metabase/metabase#87252 · 1 comentario ·
Los mantenedores suelen responder en 1 día