【Xcode 10】如何將真機的framework與模擬器的的framework合併呢?

承上集我們很開心的生出了真機的framework與模擬器的的framework,但是每一次測試都要在真機在模擬器之間切換,人生苦短,難到沒有其它的好辦法嗎?各位的聲音我聽到了,接下來我們就來合併它們,我們走。

合併framework

真機與模擬器資料夾

  • 根據上集build出來的framework,我們可以看到會有兩個資料夾,分別是真機的framework,跟模擬器的的framework

內容結構

  • 仔細看看,兩者的內容物好像一樣?

比較一下

  • 接下來我們利用lipo指令來比較看看有什麼不同,我們可以發現模擬器用的是x86_64架構的CPU,而真機用的是ARM架構的CPU,也就是說在手機上是不能用模擬器上的framework
lipo -info <your_framework_name>

接下來我們來合併這兩個檔案

合併編譯檔案

  • 接下來一樣利用lipo指令來合併編譯檔
lipo -create -output <new_framework_name> <x86_64_framework_name> <ARM_framework_name>
lipo -info <new_framework_name>

結合framework檔案

  • 接下來再將合併過後的編譯檔,跟模擬器framework上.swiftmodule內的檔案,放到真機的framework內,如此真機+模擬器的framework就完成了

一鍵合併framework

新增Aggregate Target

  • 反正步驟都相同,為何不使用shell指令去做重複的事呢?

取個好名字

新增Script

  • 新增完之後,再將下面的Code貼上,記得『FRAMEWORK_NAME』要改
# Merge Script

# 1
# Set bash script to exit immediately if any commands fail.
set -e

# 2
# Setup some constants for use later on.
FRAMEWORK_NAME="<Your_Framework_Name>"

# 3
# If remnants from a previous build exist, delete them.
if [ -d "${SRCROOT}/build" ]; then
rm -rf "${SRCROOT}/build"
fi

# 4
# Build the framework for device and for simulator (using all needed architectures).
xcodebuild -target "${FRAMEWORK_NAME}" -configuration Release -arch arm64 -arch armv7 -arch armv7s only_active_arch=no defines_module=yes -sdk "iphoneos"
xcodebuild -target "${FRAMEWORK_NAME}" -configuration Release -arch x86_64 -arch i386 only_active_arch=no defines_module=yes -sdk "iphonesimulator"

# 5
# Remove .framework file if exists on Desktop from previous run.
if [ -d "${HOME}/Desktop/${FRAMEWORK_NAME}.framework" ]; then
rm -rf "${HOME}/Desktop/${FRAMEWORK_NAME}.framework"
fi

# 6
# Copy the device version of framework to Desktop.
cp -r "${SRCROOT}/build/Release-iphoneos/${FRAMEWORK_NAME}.framework" "${HOME}/Desktop/${FRAMEWORK_NAME}.framework"

# 7
# Replace the framework executable within the framework with a new version created by merging the device and simulator # frameworks' executables with lipo.

lipo -create -output "${HOME}/Desktop/${FRAMEWORK_NAME}.framework/${FRAMEWORK_NAME}" "${SRCROOT}/build/Release-iphoneos/${FRAMEWORK_NAME}.framework/${FRAMEWORK_NAME}" "${SRCROOT}/build/Release-iphonesimulator/${FRAMEWORK_NAME}.framework/${FRAMEWORK_NAME}"

# 8 # Copy the Swift module mappings for the simulator into the # framework. The device mappings already exist from step 6.
cp -r "${SRCROOT}/build/Release-iphonesimulator/${FRAMEWORK_NAME}.framework/Modules/${FRAMEWORK_NAME}.swiftmodule/" "${HOME}/Desktop/${FRAMEWORK_NAME}.framework/Modules/${FRAMEWORK_NAME}.swiftmodule"

# 9
# Delete the most recent build.
if [ -d "${SRCROOT}/build" ]; then
rm -rf "${SRCROOT}/build"
fi

build framework

  • 切換Target => Run => Framework就會出現在桌面上了。這麼簡單,那為什麼我不早點說呢?因為要騙稿費嘛…XD

範例程式碼下載