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

tflite-react-native安卓运行正常iOS报loadModel空对象错误如何解决

解决方案

1. 对齐模块版本,修复链接失效问题

你当前安装的npm包tflite-react-native版本为0.0.5,但Pod依赖里的TfliteReactNative版本为0.0.4,版本不匹配导致原生模块没有正确绑定,是触发本次报错的核心原因:

  • 删除项目根目录下的node_modules文件夹、package-lock.json/yarn.lock文件
  • 执行npm install tflite-react-native@0.0.4 --save或yarn add tflite-react-native@0.0.4对齐双端版本
  • 进入ios目录,依次执行pod deintegrate、删除Podfile.lock文件、pod install完成依赖重装

2. 正确配置iOS端模型资源

iOS的静态资源不会自动读取文件夹路径,需要手动加入应用的编译资源列表:

  1. 用Xcode打开项目下的.xcworkspace文件,右击左侧项目导航栏的项目根目录,选择「Add Files to [你的应用名]」
  2. 找到/ios/[app_name]/models/文件夹,勾选「Copy items if needed」,添加方式选择「Create groups」,必须勾选Add to targets列表里的应用主目标
  3. 进入项目设置的「Build Phases」标签,展开「Copy Bundle Resources」,确认model.tflite和labels.txt已在资源列表内,不在的话手动拖入补充

3. 调整代码适配双端路径与初始化时序

iOS端读取bundle内资源不需要加文件夹前缀,同时建议将模型加载逻辑从constructor移到componentDidMount避免初始化时序问题:

// 头部引入Platform模块
import { Platform, Component } from 'react-native';
import Tflite from 'tflite-react-native';

let tflite = new Tflite();
// 区分双端路径
var modelFile = Platform.OS === 'ios' ? 'model.tflite' : 'models/model.tflite';
var labelsFile = Platform.OS === 'ios' ? 'labels.txt' : 'models/labels.txt';

export default class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      recognitions: null,
      source: null,
    };
  }

  componentDidMount() {
    tflite.loadModel({model: modelFile, labels: labelsFile}, (err, res) => {
      if (err) console.log(err);
      else console.log(res);
    });
  }
 ...
}

4. 清理缓存重新运行

执行npx react-native start --reset-cache清空 Metro 打包缓存,再重新执行npx react-native run-ios即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 03:27:03