広告 Flutter Dart アプリ開発

iOSでtensorflowliteとカメラ、openCVを使ったときの覚書

iOSでtensorflowLiteやOpenCV等のC++ライブラリを使ったときに大変苦労したので、作業内容を記録しておく

tflite_flutterに関する注意

Android

android/app/build.gradle.kts に以下のように記述し、圧縮しないように設定する必要があった。

android {
    // ... 他の設定 (namespace, compileSdk など) ...

    // ▼ ここから追加 ▼
    aaptOptions {
        noCompress("tflite")  // 括弧とダブルクォートが必要です
    }
    // ▲ ここまで追加 ▲

    // ... defaultConfig など ...
}

iOS

ios/Podfileの修正で、ターゲットプラットフォームを12以上にする必要があった。(以下の例は13にしている)赤字が重要

# Uncomment this line to define a global platform for your project
platform :ios, '13.0'

# CocoaPods analytics sends network stats synchronously affecting flutter build latency.
ENV['COCOAPODS_DISABLE_STATS'] = 'true'

project 'Runner', {
  'Debug' => :debug,
  'Profile' => :release,
  'Release' => :release,
}

def flutter_root
  generated_xcode_build_settings_path = File.expand_path(File.join('..', 'Flutter', 'Generated.xcconfig'), __FILE__)
  unless File.exist?(generated_xcode_build_settings_path)
    raise "#{generated_xcode_build_settings_path} must exist. If you're running pod install manually, make sure flutter pub get is executed first"
  end

  File.foreach(generated_xcode_build_settings_path) do |line|
    matches = line.match(/FLUTTER_ROOT\=(.*)/)
    return matches[1].strip if matches
  end
  raise "FLUTTER_ROOT not found in #{generated_xcode_build_settings_path}. Try deleting Generated.xcconfig, then run flutter pub get"
end

require File.expand_path(File.join('packages', 'flutter_tools', 'bin', 'podhelper'), flutter_root)

flutter_ios_podfile_setup

target 'Runner' do
  use_frameworks!

  flutter_install_all_ios_pods File.dirname(File.realpath(__FILE__))
  pod 'TensorFlowLiteC'

  target 'RunnerTests' do
    inherit! :search_paths
  end
end

post_install do |installer|
  installer.pods_project.targets.each do |target|
    flutter_additional_ios_build_settings(target)
    target.build_configurations.each do |config|
      # 全ての Pods のターゲットをプロジェクトと合わせる(例: 13.0)
      config.build_settings['IPHONEOS_DEPLOYMENT_TARGET'] = '13.0'
    end
  end
end

Podfileを修正したら、必ず「pod install」を実行する必要がある。lockファイルを消してから行う

cd ios
rm -rf Podfile.lock
pod install
..

tfliteのファイル名は「model.tflite」のようにシンプルにする。

アセットのパスは「assets/model.tflite」で正しい(ChatGPTは、間違っている)下記手順でよい。
もちろんpubspec.yamlに、「 - assets/model.tflite」の設定は必須。インデントの位置も重要。

import 'package:tflite_flutter/tflite_flutter.dart';

Future<void> loadModel() async {
  try {
    // 'assets/' を含めたパスを指定
    final interpreter = await Interpreter.fromAsset('assets/model.tflite');
    
    print('モデルの読み込みに成功しました');
  } catch (e) {
    print('モデルの読み込みエラー: $e');
  }
}

MacOSでは、「flutter build ios --release」を問題なく実行出来た後に、XcodeでC++モジュールを使う場合に以下の設定が必要

  1. Xcodeで Runner.xcworkspace を開く。
  2. 左側のナビゲーターで Runner プロジェクトを選択。
  3. TARGETSRunner を選択。
  4. Build Settings タブを開く。
  5. 検索バーに Strip Style と入力。
  6. Strip Style の設定を Non-Global Symbols に変更。(デフォルトは All Symbols になっている)
  7. Strip Linked ProductNo に設定。

other Linker Flagsに色々設定が必要。

  1. Xcodeで Runner ターゲットを選択。
  2. Build Settings タブを開く。
  3. 検索バーに Other Linker Flags と入力。
  4. 項目をダブルクリックして、リスト編集モードにする。
  5. + ボタンを押して、以下の文字列を追加(1行で入力)。
    -force_load $(SRCROOT)/Pods/TensorFlowLiteC/Frameworks/TensorFlowLiteC.framework/TensorFlowLiteC

(事前に「flutter build ios --release」を実行すると、自動的にother Linker Flags等に色々設定がされるっぽい。Xcodeで確認すること。)

model.tfliteファイルを確実にパッケージに同梱させる設定(念の為)

  1. Xcodeで ios/Runner.xcworkspace を開く。
  2. 左側のナビゲーターで Runner(フォルダアイコン)を右クリックし、"Add Files to 'Runner'..." を選択。
  3. model.tflite を選択。
  4. Destination: "Copy items if needed" にチェックを入れる。
  5. Added folders: "Create groups" を選択。
  6. Add to targets: "Runner" にチェックを入れる。
  7. Build PhasesCopy Bundle Resourcesmodel.tflite が追加されているのを確認。

ArchveをAppStoreにアップロードさせる画面で、ファイルとしてエクスポートすると、ちゃんとパッケージされているか確認することができる。(ファイル拡張子をipaからzipに変更すると解凍できる)

IPAファイルとして書き出して確認

実際の配布形式(.ipa)を作って確認する方法です。署名周りのエラーも含めて最終確認したい場合はこちら。

  1. オーガナイザで「Distribute App」
    • Organizer画面右側の [Distribute App] ボタンを押す。
  2. 書き出し設定
    • Custom(または Development / Ad Hoc)を選択。※App Store Connectを選ぶとアップロードされてしまうので注意。
    • App Store ではなく Development を選ぶと、署名の検証が緩く、処理が速い。
    • ひたすら「Next」を押し、最後に Export を選び、デスクトップなどに保存。
  3. IPAを解凍する
    • 保存されたフォルダの中に Runner.ipa がある。
    • この拡張子 .ipa.zip に書き換える。
    • 「拡張子を変更しますか?」と聞かれるので「.zip を使用」を選ぶ。
    • ダブルクリックして解凍。
  4. 中身を確認
    • Payload フォルダが生成される。
    • その中の Runner.app右クリック > パッケージの内容を表示
    • Frameworks/App.framework/flutter_assets/...を確認

カメラを使うための設定

Android

android/app/build.gradle.ktsでNDKバージョンを指定するのみ。

android {
    ndkVersion = "27.0.12077973" // 開発時期により適切なものを選ぶ(新しすぎても良くない)
    ...
    defaultConfig {
        // カメラパッケージを使用する場合、21以上に設定する必要があります
        minSdk = 21 
        
        targetSdk = flutter.targetSdkVersion
        versionCode = flutterVersionCode.toInt()
        versionName = flutterVersionName
    }
    ...
}

最近のカメラモジュールは、android/app/src/main/AndroidManifest.xmlに追記は不要らしい。

iOS

ios/Runner/Info.plist ファイルを開き、<dict> タグの中に以下のキーを追加

<key>NSCameraUsageDescription</key>
<string>This app requires camera access to take photos and videos.</string>

<key>NSMicrophoneUsageDescription</key>
<string>This app requires microphone access to record audio during video capture.</string>

<key>NSPhotoLibraryUsageDescription</key>
<string>This app requires access to your photo library to save and select photos.</string>

MacOSのCMake4問題

open_cvは2026年2月時点では、cmake 4.x.x に未対応。CMake4.xは、破壊的更新があったらしい。

Ubuntuは「sudo apt install cmake」とすると、標準でver3.28.3がインストールされるので問題なかった。

MacOSはOS26(Tahoma)だと、「brew install cmake」とするとcmake 4.xが入ってしまうので問題あり

CMakeの公式サイトに行き

https://cmake.org/download

レガシーリリース (3.31.11)から

「Platform」で macOS 10.13 or later を探し、.dmg ファイル(例: cmake-3.30.0-macos-universal.dmg)をダウンロードしインストールする。

その後、以下のシンボリックリンクが必要。

sudo "/Applications/CMake.app/Contents/bin/cmake-gui" --install

which cmake と入力して見つかればOK(/usr/local/bin/cmake)

「cmake --version」 で3.31.11と表示されればOK

なお、以下のコマンドでFlutterでiosのビルドがエラーなく出来れば、FlutterとCMakeには問題ない (後はXCodeの設定が重要)

flutter build ios --release

-Flutter Dart アプリ開発