Xcode中CoreML模型加载失败:无法读取模型包,缺少有效清单
iOS CoreML模型加载失败:Manifest.json不存在错误
我原本计划开发一款iOS端的简单图片选择器,加载图片后输出带百分比的分析结果,但目前CoreML模型无法加载,程序崩溃并报错:
Vision___CoreML/MainViewController.swift:34: Fatal error: Unable to load model: Failed to read model package at ... Error: A valid manifest does not exist at path: .../companyLogos.mlmodelc/Manifest.json
我尝试过在Copy Bundle Resources和Compile Resources中添加、移除并重新添加.mlmodelc文件,但均未解决问题。
以下是完整代码:
import UIKit import Vision class MainViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate { @IBOutlet var imgGuess: UIImageView! @IBOutlet var lblGuess: UILabel! override func viewDidLoad() { super.viewDidLoad() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any]) { if let pickedImage = info[.originalImage] as? UIImage { lblGuess.text = "Thinking" imgGuess.contentMode = .scaleAspectFit imgGuess.image = pickedImage // Load the model using the recommended method guard let modelURL = Bundle.main.url(forResource: "companyLogos", withExtension: "mlmodelc"), let model = try? VNCoreMLModel(for: MLModel(contentsOf: modelURL, configuration: MLModelConfiguration())) else { fatalError("Unable to load model") } let request = VNCoreMLRequest(model: model) { [weak self] request, error in if let error = error { print("❌ Error during Vision request: \(error)") return } print("🔍 Raw Results:", request.results ?? "No results") guard let results = request.results as? [VNClassificationObservation] else { fatalError("❌ Model did not return classification results! Check the model type.") } guard let topResult = results.first else { print("❌ No classification results found.") return } DispatchQueue.main.async { [weak self] in self?.lblGuess.text = "\(topResult.identifier) with \(Int(topResult.confidence * 100))% confidence" } } guard let ciImage = CIImage(image: pickedImage) else { fatalError("Cannot read picked image") } let handler = VNImageRequestHandler(ciImage: ciImage) DispatchQueue.global().async { do { try handler.perform([request]) } catch { print(error) } } picker.dismiss(animated: true, completion: nil) print("✅ Bild erfolgreich geladen") } else { print("❌ Kein Bild erhalten!") } } @IBAction func takePhoto(_ sender: Any) { if UIImagePickerController.isSourceTypeAvailable(.photoLibrary) { let imagePicker = UIImagePickerController() imagePicker.delegate = self imagePicker.sourceType = .photoLibrary imagePicker.allowsEditing = false self.present(imagePicker, animated: true, completion: nil) } } @IBAction func takePhotoFromCamera(_ sender: Any) { if UIImagePickerController.isSourceTypeAvailable(.camera) { let imagePicker = UIImagePickerController() imagePicker.delegate = self imagePicker.sourceType = .camera imagePicker.allowsEditing = false self.present(imagePicker, animated: true, completion: nil) } } }
解决方案
- 禁止手动操作.mlmodelc文件:Xcode会自动编译
.mlmodel源文件生成.mlmodelc包,手动添加/移除会破坏文件结构。直接将.mlmodel文件拖入项目,勾选对应目标工程。 - 检查模型编译配置:选中
.mlmodel文件,右侧检查器确认Target Membership已勾选当前工程,Compile Source保持默认的CoreMLModelCompiler。 - 优化模型加载代码:使用Xcode自动生成的模型类加载,避免手动拼接路径:
注意:// 替换原加载代码 guard let model = try? VNCoreMLModel(for: companyLogos(configuration: MLModelConfiguration()).model) else { fatalError("Unable to load model") }companyLogos是根据你的.mlmodel文件名自动生成的类名,确保大小写一致。 - 清理重建项目:执行
Cmd+Shift+K清理构建文件夹,删除设备上的App后重新编译运行。 - 验证模型完整性:右键
.mlmodel文件选择Show in Finder,查看DerivedData中生成的.mlmodelc包是否包含Manifest.json,若缺失需重新获取正确的CoreML模型。
内容的提问来源于stack exchange,提问作者morry239
相关产品推荐
相关产品推荐

