Skip to content

Instantly share code, notes, and snippets.

@the-yuyut
Last active November 14, 2022 02:57
Show Gist options
  • Select an option

  • Save the-yuyut/e0a518ed9b1c982f09557d82317c8de5 to your computer and use it in GitHub Desktop.

Select an option

Save the-yuyut/e0a518ed9b1c982f09557d82317c8de5 to your computer and use it in GitHub Desktop.
Solution of make XCFramework from Swift Package

before execute, gen xcode project by

swift package generate-xcodeproj

and configure the build setting as you need

then excute the script with two argument

  1. the name of .xcodeproj
  2. the sheme to gen (may be different due to auto generate xcode project)
sh build.sh XCODEPROJNAME_OF_THE_PROJECT LIBRARY_SCHEME
#!/bin/bash
set -x
set -e
# Pass scheme name as the first argument to the script
PROJECT=$1
NAME=$2
# Build the scheme for all platforms that we plan to support
for PLATFORM in "iOS Simulator" "macOS" ; do
case $PLATFORM in
"macOS")
RELEASE_FOLDER="Release-macos"
;;
"iOS")
RELEASE_FOLDER="Release-iphoneos"
;;
"iOS Simulator")
RELEASE_FOLDER="Release-iphonesimulator"
;;
esac
ARCHIVE_PATH=$RELEASE_FOLDER
# Rewrite Package.swift so that it declaras dynamic libraries, since the approach does not work with static libraries
perl -i -p0e 's/type: .static,//g' Package.swift
perl -i -p0e 's/type: .dynamic,//g' Package.swift
perl -i -p0e 's/(library[^,]*,)/$1 type: .dynamic,/g' Package.swift
xcodebuild archive -project ${PROJECT}.xcodeproj -scheme $NAME \
-destination "generic/platform=${PLATFORM}" \
-archivePath $ARCHIVE_PATH \
-derivedDataPath ".build" \
ENABLE_TESTING_SEARCH_PATHS=YES \
SKIP_INSTALL=NO \
BUILD_LIBRARY_FOR_DISTRIBUTION=YES
FRAMEWORK_PATH="$ARCHIVE_PATH.xcarchive/Products/usr/local/lib/$NAME.framework"
MODULES_PATH="$FRAMEWORK_PATH/Modules"
mkdir -p $MODULES_PATH
BUILD_PRODUCTS_PATH=".build/Build/Intermediates.noindex/ArchiveIntermediates/$NAME/BuildProductsPath"
RELEASE_PATH="$BUILD_PRODUCTS_PATH/$RELEASE_FOLDER"
SWIFT_MODULE_PATH="$RELEASE_PATH/$NAME.swiftmodule"
RESOURCES_BUNDLE_PATH="$RELEASE_PATH/${NAME}_${NAME}.bundle"
# Copy Swift modules
if [ -d $SWIFT_MODULE_PATH ]
then
cp -r $SWIFT_MODULE_PATH $MODULES_PATH
else
# In case there are no modules, assume C/ObjC library and create module map
echo "module $NAME { export * }" > $MODULES_PATH/module.modulemap
# TODO: Copy headers
fi
# Copy resources bundle, if exists
if [ -e $RESOURCES_BUNDLE_PATH ]
then
cp -r $RESOURCES_BUNDLE_PATH $FRAMEWORK_PATH
fi
done
xcodebuild -create-xcframework \
-framework Release-macos.xcarchive/Products/Library/Frameworks/$PROJECT.framework \
-framework Release-iphonesimulator.xcarchive/Products/Library/Frameworks/$PROJECT.framework \
-output $PROJECT.xcframework
@the-yuyut
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment