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

Swift 3与Xcode 8.3.3下UIImagePickerController选图报错如何解决?

解决UIImagePickerController选图时的nil崩溃和图片格式错误问题

Hey there, let's work through your problem step by step—since you're using Swift 3 with Xcode 8.3.3 and hitting two frustrating issues: the "Creating an image format with an unknown type is an error" warning, and a crash from unexpectedly found nil when assigning to self?.imgView.image.

首先解决「unexpectedly found nil」崩溃问题

This is the critical one causing your app to crash, and it means self.imgView is nil when you try to set its image. Here's how to fix it:

  • Check your IBOutlet connection:

    • Open your Storyboard/XIB and make sure the imgView outlet is properly connected to your UIImageView. Look for the hollow circle next to the @IBOutlet declaration in your ViewController code—if it's hollow, the connection is missing. Double-check that the outlet name matches exactly between your code and the Storyboard element's "Referencing Outlets" section.
  • Ensure imgView is initialized (if using code-only setup):
    If you're creating imgView programmatically instead of using Storyboards, make sure you've initialized it and added it to your view hierarchy before calling takePhoto. For example:

    override func viewDidLoad() {
        super.viewDidLoad()
        // Initialize and add imgView to the view
        imgView = UIImageView(frame: CGRect(x: 20, y: 20, width: 200, height: 200))
        view.addSubview(imgView)
    }
    
  • Add a safety check in takePhoto:
    To avoid crashes even if something goes wrong, add a guard statement to verify imgView exists before assigning the image:

    func takePhoto(newImage: UIImage) {
        guard let imageView = self.imgView else {
            print("Error: imgView is nil! Check IBOutlet or initialization.")
            return
        }
        imageView.image = newImage
    }
    

解决「Creating an image format with an unknown type is an error」警告

This warning usually pops up when the selected image has an uncommon format (like HEIC, which had limited support in older Xcode versions) or corrupted EXIF data. Try these fixes:

  • Convert the image to a standard format:
    In your UIImagePickerControllerDelegate method, convert the picked image to JPEG or PNG before passing it to takePhoto. This ensures the image uses a widely supported format:

    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        picker.dismiss(animated: true, completion: nil)
        
        guard let originalImage = info[UIImagePickerControllerOriginalImage] as? UIImage else {
            print("Failed to retrieve selected image")
            return
        }
        
        // Convert to JPEG to resolve format issues
        if let jpegData = UIImageJPEGRepresentation(originalImage, 0.8), let formattedImage = UIImage(data: jpegData) {
            takePhoto(newImage: formattedImage)
        } else {
            // Fallback to original if conversion fails
            takePhoto(newImage: originalImage)
        }
    }
    
  • Fix image orientation issues:
    Some images have incorrect EXIF orientation data, which can trigger format warnings. Use this helper method to correct the image's orientation:

    func correctedOrientationImage(_ image: UIImage) -> UIImage {
        guard image.imageOrientation != .up else { return image }
        
        UIGraphicsBeginImageContextWithOptions(image.size, false, image.scale)
        image.draw(in: CGRect(origin: .zero, size: image.size))
        let correctedImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        
        return correctedImage ?? image
    }
    

    Then use it in your delegate method:

    let fixedImage = correctedOrientationImage(originalImage)
    takePhoto(newImage: fixedImage)
    

Final Quick Checks

  • Make sure your ViewController conforms to both UIImagePickerControllerDelegate and UINavigationControllerDelegate protocols.
  • Verify that you've added the NSPhotoLibraryUsageDescription key to your Info.plist with a brief explanation of why you need photo library access (required for iOS 10+).

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 03:28:18