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

Đang mở
#94 0 bình luận 0 reaction 0 người được giao Xem trên GitHub

Chưa có ai nhận issue này.

Đánh giá

Độ khó
4/5
Thời gian dự kiến
3-5 ngày
Mức phù hợp với người mới
45/100
Loại issue
Lỗi
Độ rõ ràng
Đặc tả rõ ràng
Mức độ hoạt động
Sôi nổi
Công nghệ
ios, swift
Lĩnh vực
mobile

Hướng nghiên cứu

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.

Do mô hình lập chỉ mục viết ra từ nội dung của issue.

Mô tả

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)
+        }
+    }
+}
Ngôn ngữ chính
TypeScript
Star
6
Fork
4
Merge trung bình
2 ngày 11 giờ
Pull request đã merge (30 ngày)
6

Chuẩn bị môi trường

Bắt đầu từ đâu

  1. Đọc hết issue, rồi đọc hướng dẫn đóng góp của dự án.
  2. Bình luận trên issue rằng bạn sẽ nhận — tránh hai người làm cùng một việc.
  3. Fork repository và làm thay đổi trên một nhánh.
  4. Mở pull request có tham chiếu số hiệu của issue.

Issue khác của ionic-team/capacitor-camera

Tất cả issue của ionic-team/capacitor-camera

Issue tương tự

Thêm issue về TypeScript

Nhận issue mới trong hộp thư của bạn

Bản tóm tắt ngắn những issue GitHub phù hợp với người mới.