You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift配置隐私权限后访问相册UIImagePickerController仍崩溃

Fixing UIImagePickerController Crash in Swift 4 (Photo Library)

Hey there, let's tackle this crash you're hitting when trying to present a UIImagePickerController with .photoLibrary source type. The error unrecognized selector sent to instance with encodeWithCoder: is a classic sign that something's wrong with the delegate object's lifecycle or protocol conformance. Let's break it down step by step.

Why This Crash Happens

The root cause here is that the UIImagePickerController is trying to send messages to its delegate (your view controller, self), but that delegate object has already been deallocated from memory. When ARC releases the view controller, the memory it occupied gets reused for another object (hence the __NSCFType in the error log), leading to an invalid selector call.

Another common oversight is forgetting to conform to all required protocols for the picker's delegate.

Step-by-Step Fixes

1. Ensure You Conform to Both Required Protocols

UIImagePickerControllerDelegate inherits from UINavigationControllerDelegate, but it's still critical to explicitly declare both in your view controller's class definition (or extension). Missing either can lead to runtime inconsistencies.

Update your view controller like this:

class YourViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    // Your existing code here
}

Or use an extension to keep your code clean:

extension YourViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    // Implement picker delegate methods here
}

2. Verify the Delegate Object's Lifecycle

Make sure your view controller (self) stays alive for as long as the UIImagePickerController is presented. Here are common pitfalls to check:

  • Avoid presenting from temporary objects: If you're creating the view controller in a local scope (like a closure or helper method) without holding a strong reference to it, it might get deallocated before the picker finishes.
  • Check for weak references: If self is being referenced weakly somewhere (e.g., in a closure), ensure that the reference is still valid when the picker tries to communicate with it.
  • Always dismiss the picker: Make sure you implement both didFinishPickingMediaWithInfo and imagePickerControllerDidCancel to dismiss the picker properly—leaving it presented can lead to unexpected memory issues.

3. Example of Correct Implementation

Here's a complete, working example to reference:

class PhotoPickerDemoVC: UIViewController {

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        // Trigger the picker (could also be tied to a button tap)
        presentPhotoPicker()
    }

    func presentPhotoPicker() {
        let picker = UIImagePickerController()
        picker.delegate = self
        picker.sourceType = .photoLibrary
        
        // Always check if the source type is available (optional but safe)
        guard UIImagePickerController.isSourceTypeAvailable(.photoLibrary) else {
            print("Photo library is not available")
            return
        }
        
        present(picker, animated: true)
    }
}

// MARK: - UIImagePickerController Delegates
extension PhotoPickerDemoVC: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        // Handle the selected image
        if let originalImage = info[.originalImage] as? UIImage {
            print("Selected image: \(originalImage.size)")
            // Do something with the image (e.g., display it, upload it)
        }
        
        // Dismiss the picker
        picker.dismiss(animated: true)
    }

    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        // Dismiss the picker when user cancels
        picker.dismiss(animated: true)
    }
}

Final Notes

Since you already added the privacy permissions in info.plist (good call!), we can rule that out as the cause. The crash is 99% related to delegate protocol conformance or memory management of your view controller.

内容的提问来源于stack exchange,提问作者Hla Khader

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 07:56:48