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

SwiftUI集成CoreML报错:检查模型路径时无法获取主目录

解决"Failed to get the home directory when checking model path"错误

这个错误的核心问题是Core ML模型文件没有被正确集成到项目中,导致App运行时无法定位到模型路径。按以下步骤排查修复:

1. 确认模型已添加到项目

检查项目导航栏中是否存在SleepCalculator.mlmodel文件。如果缺失,重新获取教程中的模型文件,拖拽到Xcode项目内,拖拽时务必勾选Copy items if needed,并确保选中你的App Target(比如项目名BetterRest)。

2. 检查模型的Target Membership

选中SleepCalculator.mlmodel文件,打开右侧的File Inspector面板,在Target Membership区域,确认你的主App Target的复选框处于勾选状态——这是模型能被打包进App的关键。

3. 可选:显式指定模型路径初始化

如果前两步完成后仍报错,可以尝试通过Bundle路径显式加载模型,替换原有的模型初始化代码:

do {
    let config = MLModelConfiguration()
    guard let modelURL = Bundle.main.url(forResource: "SleepCalculator", withExtension: "mlmodelc") else {
        alertTitle = "模型缺失"
        alertMessage = "找不到SleepCalculator模型文件"
        showingAlert = true
        return
    }
    let model = try SleepCalculator(contentsOf: modelURL, configuration: config)
    // 后续预测代码保持不变
    let components = Calendar.current.dateComponents([.hour, .minute], from: wakeUp)
    let hour = (components.hour ?? 0) * 60 * 60
    let minute = (components.minute ?? 0) * 60
    let prediction = try model.prediction(wake:Int64(hour + minute), estimatedSleep: sleepAmount, coffee: Int64(coffeeAmount))
    let sleepTime = wakeUp - prediction.actualSleep
    alertTitle = "Your ideal bedtime is ..."
    alertMessage = sleepTime.formatted(date: .omitted, time: .shortened)
    showingAlert = true
} catch {
    alertTitle = "计算失败"
    alertMessage = "错误详情:\(error.localizedDescription)"
    showingAlert = true
    print(error) // 控制台打印完整错误,方便调试
}

额外调试步骤

  • 清理项目缓存:点击Xcode顶部菜单 Product > Clean Build Folder,之后重新构建运行。
  • 检查模型文件是否被误移动或删除,确保它在项目目录的正确位置。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 15:00:21