前言
在開發中,經常需要將程式碼打包成為Framework,每次都手動配置合併十分麻煩,這裡提供一種使用指令碼動態生成Framework的方法。使用指令碼可以動態跟隨工程程式碼,隨時打包,簡單方便
1.新建Framework專用Target,設定打包相關配置
第一步
在工程中新建一個Target,選中Framework,用來打包Framework

第二步
選中打包Framework對應Target,找到Build Setting
,搜尋iOS,修改對應版本,必要操作

第三步
找到Dead Code Stripping
選項,設定為NO,非必要操作,建議修改

第四步
修改Link With Standard Libraries
選項,設定為NO,非必要操作,建議修改

第五步
修改Mach-O Type
選項,設定為靜態庫。非必要操作,如果要上架商店,必須是靜態庫。

第六步
設定Build Active Architecture Only
選項,修改為NO,必要操作

第七步
設定Architecture
支援armv7s
,非必要操作,看Framework是否需要支援對應架構機型

第八步
設定對外開放的.h標頭檔案,不對外開放的.h標頭檔案,放到Private
或者Project
選項下面。注意Compile Sources
選項,看看是否有對應標頭檔案的.m檔案,如果沒有需要新增進去,不然打包出來Framework會報錯,必要操作

第九步
切換到Framework對應Target的.h檔案,匯入需要暴露的.h標頭檔案,必要操作

2.新建Shell指令碼Target,加入打包Framework指令碼
第一步
新建Shell專用Target

第二步
新增指令碼Phase

第三步
加入指令碼,指令碼中的target名稱需要根據自己新建的Framework打包Targrt填寫
#!/bin/sh
#要build的target名
TARGET_NAME="CLFramework"
if [[ $1 ]]
then
TARGET_NAME=$1
fi
UNIVERSAL_OUTPUT_FOLDER="${SRCROOT}/Products"
#建立輸出目錄,並刪除之前的framework檔案
mkdir -p "${UNIVERSAL_OUTPUT_FOLDER}"
rm -rf "${UNIVERSAL_OUTPUT_FOLDER}/${TARGET_NAME}.framework"
#分別編譯模擬器和真機的Framework
xcodebuild -target "${TARGET_NAME}" ONLY_ACTIVE_ARCH=NO -configuration ${CONFIGURATION} -sdk iphoneos BUILD_DIR="${BUILD_DIR}" BUILD_ROOT="${BUILD_ROOT}" clean build
xcodebuild -target "${TARGET_NAME}" ONLY_ACTIVE_ARCH=NO -configuration ${CONFIGURATION} -sdk iphonesimulator BUILD_DIR="${BUILD_DIR}" BUILD_ROOT="${BUILD_ROOT}" clean build
#拷貝framework到univer目錄
cp -R "${BUILD_DIR}/${CONFIGURATION}-iphonesimulator/${TARGET_NAME}.framework" "${UNIVERSAL_OUTPUT_FOLDER}"
#合併framework,輸出最終的framework到build目錄
lipo -create -output "${UNIVERSAL_OUTPUT_FOLDER}/${TARGET_NAME}.framework/${TARGET_NAME}" "${BUILD_DIR}/${CONFIGURATION}-iphonesimulator/${TARGET_NAME}.framework/${TARGET_NAME}" "${BUILD_DIR}/${CONFIGURATION}-iphoneos/${TARGET_NAME}.framework/${TARGET_NAME}"
#刪除編譯之後生成的無關的配置檔案
dir_path="${UNIVERSAL_OUTPUT_FOLDER}/${TARGET_NAME}.framework/"
for file in ls $dir_path
do
if [[ ${file} =~ ".xcconfig" ]]
then
rm -f "${dir_path}/${file}"
fi
done
#判斷build資料夾是否存在,存在則刪除
if [ -d "${SRCROOT}/build" ]
then
rm -rf "${SRCROOT}/build"
fi
rm -rf "${BUILD_DIR}/${CONFIGURATION}-iphonesimulator" "${BUILD_DIR}/${CONFIGURATION}-iphoneos"
#開啟合併後的資料夾
open "${UNIVERSAL_OUTPUT_FOLDER}"
複製程式碼
3.使用Shell打包Framework
選中Shell指令碼對應的Target,選擇通用,執行程式碼,選擇機型的時候,一定要選擇通用,這樣才會包含模擬器和真機。

總結
打包完成後,可以通過lipo -info
命令檢視打包出來的Framework支援哪些架構的機型,Demo地址-------->>CLFrameworkDemo