Flutter iOS не может быть собран из-за настроек модульного заголовка в podfile

У меня есть флаттер-приложение, которое работает нормально. Я обновляю свою версию флаттера и версии некоторых моих плагинов (в новейшей версии XCode 11). Я больше не могу создавать свое приложение, потому что происходит одно из двух:

1) Если у меня нет "use_modular_headers!" в моем подфайле я получаю эту ошибку при попытке запустить pod install:

The Swift pod `DKPhotoGallery` depends upon `SDWebImage`, which does not define modules. To opt into those targets generating module maps (which is necessary to import them from Swift when building as static libraries), you may set `use_modular_headers!` globally in your Podfile, or specify `:modular_headers => true` for particular dependencies.

2) Если я добавлю "use_modular_headers!" в подфайл, то я могу успешно установить подфайлы, но при сборке возникает ошибка:

fatal error: module map file '/Users/mbpro/Documents/Perkl/ios/Pods/Headers/Private/openssl_grpc/BoringSSL-GRPC.modulemap' not found

Вторая ошибка, которую я обнаружил, заключается в том, что GRPC не поддерживает модульные заголовки. Здесь я застрял, потому что из-за того, что флаттер динамически генерирует подфайл из pubspec, кажется, что модульные заголовки либо глобально включены, либо выключены, и я не могу специально включить модульные заголовки для определенных модулей.

Вот список моих зависимостей pubspec:

  cloud_firestore: 0.13.6
  firebase_auth: 0.16.1
  firebase_core:
  firebase_database:
  firebase_storage:
  firebase_messaging:
  google_sign_in:
  image_picker:
  image_cropper:
  intl:
  flutter_sound:
  flutter_launcher_icons:
  flushbar:
  file_picker:
  path_provider:
  #audioplayers:
  provider:
  sliding_up_panel:
  font_awesome_flutter:
  marquee:

Любая помощь в этом будет принята с благодарностью! Это полностью остановило мою разработку, так как я не могу ничего протестировать после обновления.

Редактировать: вывод Flutter Doctor -v (все выглядит нормально)

[✓] Flutter (Channel stable, v1.17.3, on Mac OS X 10.15.5 19F101, locale en-US)
    • Flutter version 1.17.3 at /Users/mbpro/Downloads/flutter
    • Framework revision b041144f83 (8 days ago), 2020-06-04 09:26:11 -0700
    • Engine revision ee76268252
    • Dart version 2.8.4


[✓] Android toolchain - develop for Android devices (Android SDK version 29.0.2)
    • Android SDK at /Users/mbpro/Library/Android/sdk
    • Platform android-29, build-tools 29.0.2
    • Java binary at: /Applications/Android
      Studio.app/Contents/jre/jdk/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build
      1.8.0_202-release-1483-b49-5587405)
    • All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS (Xcode 11.5)
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • Xcode 11.5, Build version 11E608c
    • CocoaPods version 1.9.3

[✓] Android Studio (version 3.5)
    • Android Studio at /Applications/Android Studio.app/Contents
    • Flutter plugin version 44.0.1
    • Dart plugin version 191.8593
    • Java version OpenJDK Runtime Environment (build
      1.8.0_202-release-1483-b49-5587405)

[✓] Connected device (1 available)
    • iPhone SE (2nd generation) • 9FC22937-91AB-4F22-BB1E-20FFB1CAF4C8 • ios •
      com.apple.CoreSimulator.SimRuntime.iOS-13-5 (simulator)

• No issues found!

person Kyle B.    schedule 12.06.2020    source источник
comment
Вы можете запустить «флаттер-доктор» и вставить результат в свой вопрос?   -  person gg11    schedule 12.06.2020
comment
Я сделал правку, но в флаттер-докторе все в порядке. Похоже, что один из моих плагинов для дротиков использует фреймворк iOS, который не может использовать модульные заголовки, в то время как другой использует библиотеку iOS, которая должна использовать модульные заголовки. Но с тем, как флаттер имеет настройку podfile, вы не можете указать только определенным модулям использовать модульные заголовки.   -  person Kyle B.    schedule 12.06.2020


Ответы (3)


После очень долгих поисков ответ прост.

1- перейдите в каталог ios внутри вашего приложения

2- редактировать подфайл в текстовом редакторе

3- найдите target 'Runner' do

4- добавить use_frameworks! в следующей строке

5- сохраните и запустите приложение

например, мой полный podfile выглядит так до решения проблемы

# Uncomment this line to define a global platform for your project
# platform :ios, '9.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

  flutter_install_all_ios_pods File.dirname(File.realpath(__FILE__))
end

post_install do |installer|
  installer.pods_project.targets.each do |target|
    flutter_additional_ios_build_settings(target)
  end
end

После решения проблемы путем добавления дополнительной строки, которая выглядит так

# Uncomment this line to define a global platform for your project
# platform :ios, '9.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__))
end

post_install do |installer|
  installer.pods_project.targets.each do |target|
    flutter_additional_ios_build_settings(target)
  end
end
person Shady Mohamed Sherif    schedule 20.10.2020
comment
Работал как шарм! - person Michał Dobi Dobrzański; 18.04.2021
comment
Спасибо, это работает, я считаю, что эта проблема связана с file_picker, и это должен быть принятый ответ. - person Mahesh Jamdade; 30.06.2021

Я весь день боролся с той же проблемой, используя очень похожий список плагинов.

Используя этот ответ: Использование статических библиотек с CocoaPods 1.5 нет такого модуля при импорте

Мне удалось изменить модуль флаттера следующим образом и построить проект:

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

inhibit_all_warnings! # ------------------> NEW

use_frameworks! # ------------------> NEW
dynamic_frameworks = ['BoringSSL-GRPC'] # ------------------> NEW

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

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


def parse_KV_file(file, separator='=')
  file_abs_path = File.expand_path(file)
  if !File.exists? file_abs_path
    return [];
  end
  generated_key_values = {}
  skip_line_start_symbols = ["#", "/"]
  File.foreach(file_abs_path) do |line|
    next if skip_line_start_symbols.any? { |symbol| line =~ /^\s*#{symbol}/ }
    plugin = line.split(pattern=separator)
    if plugin.length == 2
      podname = plugin[0].strip()
      path = plugin[1].strip()
      podpath = File.expand_path("#{path}", file_abs_path)
      generated_key_values[podname] = podpath
     else
      puts "Invalid plugin specification: #{line}"
     end
  end
  generated_key_values
end

target 'Runner' do
  # Flutter Pod

  copied_flutter_dir = File.join(__dir__, 'Flutter')
  copied_framework_path = File.join(copied_flutter_dir, 'Flutter.framework')
  copied_podspec_path = File.join(copied_flutter_dir, 'Flutter.podspec')
  unless File.exist?(copied_framework_path) && File.exist?(copied_podspec_path)
    # Copy Flutter.framework and Flutter.podspec to Flutter/ to have something to link against if the xcode backend script has not run yet.
    # That script will copy the correct debug/profile/release version of the framework based on the currently selected Xcode configuration.
    # CocoaPods will not embed the framework on pod install (before any build phases can generate) if the dylib does not exist.

    generated_xcode_build_settings_path = File.join(copied_flutter_dir, 'Generated.xcconfig')
    unless File.exist?(generated_xcode_build_settings_path)
      raise "Generated.xcconfig must exist. If you're running pod install manually, make sure flutter pub get is executed first"
    end
    generated_xcode_build_settings = parse_KV_file(generated_xcode_build_settings_path)
    cached_framework_dir = generated_xcode_build_settings['FLUTTER_FRAMEWORK_DIR'];

    unless File.exist?(copied_framework_path)
      FileUtils.cp_r(File.join(cached_framework_dir, 'Flutter.framework'), copied_flutter_dir)
    end
    unless File.exist?(copied_podspec_path)
      FileUtils.cp(File.join(cached_framework_dir, 'Flutter.podspec'), copied_flutter_dir)
    end
  end

  # Keep pod path relative so it can be checked into Podfile.lock.
  pod 'Flutter', :path => 'Flutter'
  # Plugin Pods

  # Prepare symlinks folder. We use symlinks to avoid having Podfile.lock
  # referring to absolute paths on developers' machines.
  system('rm -rf .symlinks')
  system('mkdir -p .symlinks/plugins')
  plugin_pods = parse_KV_file('../.flutter-plugins')
  plugin_pods.each do |name, path|
    symlink = File.join('.symlinks', 'plugins', name)
    File.symlink(path, symlink)  
    pod name, :path => File.join(symlink, 'ios')
  end
end


pre_install do |installer|  # ------------------> NEW BLOCK
    installer.pod_targets.each do |pod|
puts "Evaluating static framework for pod #{pod.name}"
        if dynamic_frameworks.include?(pod.name)
            puts "Overriding the static_framework method for #{pod.name}"
            pod pod.name, :modular_headers => false        
end
    end
end

post_install do |installer|
  installer.pods_project.targets.each do |target|
      target.build_configurations.each do |config|
      config.build_settings['ENABLE_BITCODE'] = 'NO'
      end
  end
end

Это мой первый раз, когда я собираю приложение в IOS, и общее время сборки составляет около 35 м (!), Я не знаю, связано ли это с этим исправлением или что-то еще.

Также попытался сделать обратное, все динамическое и статическое DKPhotoGalley, но это приводит к сбою сборки с ошибками в коде DKPhotoGallery.

если кто-то может предложить лучший подход или понимание основной проблемы, было бы здорово.

person progress87    schedule 15.06.2020

Догадаться. Я вернул file_picker на 1.6.3+2, теперь я могу без проблем запускать свое приложение для iOS. Наслаждаться. Надеюсь, вы не используете какие-либо новые функции, добавленные в средство выбора файлов после этой версии. Мне повезло там, где я не. Я считаю, что это критическое изменение является причиной. В любом случае, это сработало для меня, надеюсь, это сработает для вас. введите здесь описание изображения

person Santiago Salmeron    schedule 24.06.2020