问题
I'm including a Swift source in my CocoaPods library for the first time. For me to get the project to compile, I need to import the generated Swift header into my Objective-C source. This takes two different forms, depending on whether the project is being built as a static library or a dynamic framework:
#ifdef BUILT_AS_FRAMEWORK
#import <UnzipKit/UnzipKit-Swift.h>
#else
// Used when built as a static library
#import "UnzipKit-Swift.h"
#endif
I'm defining BUILT_AS_FRAMEWORK
in my Xcode project for development time, but when I lint the library as a dynamic framework, and because I haven't defined that flag in the Podspec, it attempts to resolve the second import, and can't find it.
Is there a way I can define the BUILT_AS_FRAMEWORK
preprocessor macro, but only if the consuming Podfile doesn't build it as a static library?
I created issue #9101 in the CocoaPods project for this question.
回答1:
I was able to use an Xcode environment variable (PACKAGE_TYPE
) in conjunction with a pre-compilation Run Script build phase to dynamically produce a header to import, which in turn makes the correct generated Swift Header import.
generate-swift-import-header.sh
#!/bin/sh
[[ "${PACKAGE_TYPE}" = "com.apple.package-type.wrapper.framework" ]] \
&& SWIFTIMPORT="<${PRODUCT_MODULE_NAME}/${PRODUCT_MODULE_NAME}-Swift.h>" \
|| SWIFTIMPORT="\"${PRODUCT_MODULE_NAME}-Swift.h\""
if [ -z "$PODS_TARGET_SRCROOT" ]; then
PODS_TARGET_SRCROOT=${SOURCE_ROOT}
echo "Building in Xcode instead of CocoaPods. Overriding PODS_TARGET_SRCROOT with SOURCE_ROOT"
fi
_Import_text="
#ifndef GeneratedSwiftImport_h
#define GeneratedSwiftImport_h
#import ${SWIFTIMPORT}
#endif /* GeneratedSwiftImport_h */
"
echo "$_Import_text" > ${PODS_TARGET_SRCROOT}/Source/GeneratedSwiftImport.h
Podspec update
s.script_phases = { :name => "Generate UnzipKit Swift Header",
:script => "\"${PODS_TARGET_SRCROOT}\"/Scripts/generate-swift-import-header.sh",
:execution_position => :before_compile }
Library source
I replaced my conditional import with this:
#import "GeneratedSwiftImport.h"
I also ignored the GeneratedSwiftImport.h
file in Git.
来源:https://stackoverflow.com/questions/57461108/is-there-a-way-to-conditionally-define-a-podspec-property-depending-on-static-or