iosxcodecocoapodsxcode-projectxcodeproj

Cocoapods post_install, how to add target membership in Pods project


I have a Podfile, that when constructing the Pods.xcodeProj ends up with an included xcframework that is a Pods.xcodeproj file reference, that I need to add as a target reference to one of the pods built targets.

I think it's possible to do such a thing in the Podfile post_install phase, but I cannot figure out the xcodeproj gem syntax required to (A) find the Nami.xcframework reference I need to add to the target, then (B) add that file reference to the desired target (see image below for the framework I wish to adjust target membership for, I basically just want to automate checking that target membership box).

My start to this Podfile script looks like:

post_install do |installer|
    nami_target = installer.pods_project.targets { |f| f.name == "react-native-nami-sdk" }

    #Pseudocode begins here, this is what I cannot figure out
    nami_xcframework_fileref = ??
    nami_target.addBuildReference(nami_xcframework)
end

Thanks for any help on this, I've found a number of example pod file scripts but none seem to do quite what I am trying to do.

Screen shot showing framework and target membership I need to adjust in Podfile


Solution

  • I managed to figure out the full script I needed, the Podfile post_install script below does exactly what I was looking for.

    Note that a key was that while you can examine targets by using the .name property, for file references only .path will always have contents you can examine, .name is often blank. Also another key item, is that you need to add the file reference to the frameworks_build_phase aspect of the target.

    The final script (added to the end of a Podfile):

    post_install do |installer|
      puts("Attempting to add Nami.xcframework reference to react-native-nami-sdk project.")
      installer.pods_project.targets.each do |target|
        if target.name  == "react-native-nami-sdk"
          puts("Found react-native-nami-sdk target.")
          all_filerefs = installer.pods_project.files
          all_filerefs.each do |fileref|
             if fileref.path.end_with? "Nami.xcframework"
              puts("Found Nami.xcframework fileref.")
              build_phase = target.frameworks_build_phase
              puts("Determining if react-native-nami-sdk build phase needs correction.")
              unless build_phase.files_references.include?(fileref)
                puts("Adding Nami.xcframework to react-native-nami-sdk target")
                build_phase.add_file_reference(fileref)
              end
             end
          end
        end
      end
    end