iOS: chooseFromGallery asks for photo library access before the user picks anything

オープン
#94 コメント 0 件 リアクション 0 件 担当者 0 名 GitHub で見る

まだ誰も着手していません。

評価

難易度
4/5
見積もり時間
3〜5日
初心者へのやさしさ
45/100
issue の種類
バグ
明瞭さ
明確に書かれている
活発さ
活発
技術スタック
ios, swift
領域
mobile

調査の方向性

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.

索引モデルが issue の本文から書いたものです。

説明

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):

  1. CameraPlugin.chooseFromGallery calls galleryManager.chooseFromGallery(with:).
  2. IONCAMRFlowBehaviour.chooseFromGallery calls permissionsBehaviour.checkForPhotoLibrary.
  3. IONCAMRPermissionsBehaviour.checkForPhotoLibrary calls PHPhotoLibrary.requestAuthorization(for: .readWrite), which shows the system prompt the first time.
  4. Only then IONCAMRGalleryBehaviour.displayPhotoLibraryView presents the custom IONCAMRPhotoLibraryView, built on PHAsset.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

  1. Fresh install, or reset privacy: xcrun simctl privacy <udid> reset all <bundle id>.
  2. Call Camera.chooseFromGallery({ mediaType: MediaTypeSelection.Photo, allowMultipleSelection: false }).
  3. 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)
+        }
+    }
+}
主要言語
TypeScript
スター
6
フォーク
4
平均マージ
2日 11時間
マージ済み PR(30日)
6

環境構築

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

ionic-team/capacitor-camera のほかの issue

ionic-team/capacitor-camera の issue をすべて見る

似ている issue

TypeScript の issue をもっと見る

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。