5分鐘掌握iOS打包腳本

實(shí)現(xiàn)的功能

  1. 自動識別單項(xiàng)目工程和Workspace工程
  2. 指定版本號打包
  3. 動態(tài)指定簽名(可能會失斄龆谩)

1. 替換Xcode中的PackageApplication

做這個(gè)動作主要是因?yàn)樵诰幾g的過程中很容易出現(xiàn)ResourceRules.plist導(dǎo)致的錯誤搂橙,所以干脆從源頭避免這個(gè)錯誤的產(chǎn)生毒涧。

PackageApplicationPath="/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/usr/bin/PackageApplication"
if [[ ! -f "${PackageApplicationPath}_backup" ]]; then
    cp $PackageApplicationPath ${PackageApplicationPath}_backup
    cp PackageApplication $PackageApplicationPath
fi

其實(shí)很簡單,只要在原始PackageApplication中搜索@codesign_args辑畦,找到下面這段腳本

my @codesign_args = ("/usr/bin/codesign", "--force", "--preserve-metadata=identifier,entitlements,resource-rules",
                      "--sign", $opt{sign},
                      "--resource-rules=$destApp/ResourceRules.plist");

替換成

my @codesign_args;
if (-e '$destApp/ResourceRules.plist') {  # If ResourceRules.plist exists, include it in codesign arguments, for backwards compatability
    @codesign_args = ("/usr/bin/codesign", "--force", "--preserve-metadata=identifier,entitlements,resource-rules",
                      "--sign", $opt{sign},
                      "--resource-rules=$destApp/ResourceRules.plist");
} else { # If ResourceRules.plist isn't found, don't include it in the codesign arguments
    @codesign_args = ("/usr/bin/codesign", "--force", "--preserve-metadata=identifier,entitlements",
                          "--sign", $opt{sign});
}

即可酌予,相信大家看到腳本后就會發(fā)現(xiàn)是怎么回事。
要注意代碼的縮進(jìn)搂捧,不正確可能導(dǎo)致找不到PackageApplication的錯誤。

重要說明:
如果是要打包AppStore版本懂缕,還要將這個(gè)改回來允跑,否則蘋果會認(rèn)為這個(gè)ipa包不合法。

2. 定義一些變量,用于默認(rèn)設(shè)置聋丝,具體情況還得看項(xiàng)目

PlistBuddy=/usr/libexec/PlistBuddy

ProjectName="YourName"
ProjectRootDir=$(PWD -P)
Configuration="Release"
# build輸出目錄
TargetBuildDir="$ProjectRootDir/build"
# 工程的Info.plist文件路徑索烹,可能在多個(gè)targets中需要修改
PlistFilePath="$ProjectRootDir/$ProjectName/Info.plist"
VersionString=$($PlistBuddy -c "Print CFBundleVersion" $PlistFilePath)
ShortVersionString=$($PlistBuddy -c "Print CFBundleShortVersionString" $PlistFilePath)
# 打包的ipa路徑
IPAFilePath="$ProjectRootDir/ipa"
# ipa文件名
IPAFileName="$ProjectName-$VersionString.ipa"
# 描述文件路徑,用于簽名
ProvisionProfileFilePath="$IPAFilePath/xxx.mobileprovision"

3. 參數(shù)解析

執(zhí)行腳本時(shí)弱睦,可以指定參數(shù)百姓,目前支持2個(gè)參數(shù),版本號和Configuration

# 參數(shù)1:版本號
if [ x$1 != x ]; then
    echo_tip "ready to update version from $VersionString to $1"
    echo_tip "$PlistBuddy -c \"Set:CFBundleVersion $1\" \"$PlistFilePath\""
    $PlistBuddy -c "Set:CFBundleVersion $1" "$PlistFilePath"

    ShortVersionString=$(echo $1 | cut -d "." -f1-3)
    $PlistBuddy -c "Set:CFBundleShortVersionString $ShortVersionString" "$PlistFilePath"

    VersionString=$($PlistBuddy -c "Print CFBundleVersion" $PlistFilePath)
    ShortVersionString=$($PlistBuddy -c "Print CFBundleShortVersionString" $PlistFilePath)
    echo_tip "after update, version = $VersionString, short version string = $ShortVersionString"

    IPAFileName="$ProjectName-$VersionString.ipa"
fi

# 參數(shù)2:編譯配置
if [ x$2 != x ]; then
    echo_tip "set configuration = $2"
    Configuration=$2
fi

4. 解析指定的描述文件

TempPlistFilePath="$IPAFilePath/temp.plist"
if [[ -f "$TempPlistFilePath" ]]; then
        rm $TempPlistFilePath
fi

security cms -D -i $ProvisionProfileFilePath > $TempPlistFilePath
IdentityString=`/usr/libexec/PlistBuddy -c 'Print DeveloperCertificates:0' $TempPlistFilePath | \
                openssl x509 -subject -inform der|head -n 1`
CodeSignIdentity=`echo "$IdentityString" | cut -d "/" -f3 | cut -d "=" -f2`
UUID=`/usr/libexec/PlistBuddy -c "Print UUID" $TempPlistFilePath`

rm $TempPlistFilePath

這里感謝 @YoXung 提供的方法

5. 清理工程

/usr/bin/xcodebuild clean -configuration $Configuration

6. 編譯工程

mkdir -p $TargetBuildDir

# 拷貝靜態(tài)庫到Build目錄:
for path in `find "$ProjectRootDir" -name "*.a"`; do
    echo_tip "    cp $path $TargetBuildDir"
    cp $path $TargetBuildDir
done

if [[ -d "$ProjectRootDir/$ProjectName.xcworkspace" ]]; then
    /usr/bin/xcodebuild \
        -workspace $ProjectName.xcworkspace \
        -scheme $ProjectName \
        -configuration $Configuration \
        -sdk iphoneos \
        OBJROOT=$TargetBuildDir \
        TARGET_BUILD_DIR=$TargetBuildDir \
        LIBRARY_SEARCH_PATHS=$TargetBuildDir \
        CODE_SIGN_IDENTITY="$CodeSignIdentity" \
        PROVISIONING_PROFILE="$UUID"
else
    /usr/bin/xcodebuild \
        -target $ProjectName \
        -configuration $Configuration \
        -sdk iphoneos \
        OBJROOT=$TargetBuildDir \
        TARGET_BUILD_DIR=$TargetBuildDir \
        LIBRARY_SEARCH_PATHS=$TargetBuildDir \
        CODE_SIGN_IDENTITY="$CodeSignIdentity" \
        PROVISIONING_PROFILE="$UUID"
fi

ReturnCode=$(echo $?)
if ([[ $ReturnCode == "0" ]] && [[ -d "$TargetBuildDir/$ProjectName.app" ]]); then
    echo_tip "編譯成功况木!"
else
    echo_error "編譯失敗垒拢,請修改后重試!"
    exit 1
fi

這里需要注意一下:
如果腳本提示下面錯誤

Check dependencies
Code Sign error: No codesigning identities found: No codesigning identities 
(i.e. certificate and private key pairs) that match the provisioning profile 
specified in your build settings (“xxxxx”) were found.

則需要把編譯命令中的CODE_SIGN_IDENTITYPROVISIONING_PROFILE選項(xiàng)去掉火惊,然后你要正確設(shè)置工程中的證書和描述文件求类,否則打出來的包會安裝不上。

7. 打包

# 刪除已有的ipa包
if [[ -f "$IPAFilePath/$IPAFileName" ]]; then
    rm -f "$IPAFilePath/$IPAFileName"
fi

/usr/bin/xcrun -sdk iphoneos \
    PackageApplication \
        -v $TargetBuildDir/$ProjectName.app \
        -o $IPAFilePath/$IPAFileName \
        --sign "$CodeSignIdentity" \
        --embed "$ProvisionProfileFilePath"

if [[ -f "$IPAFilePath/$IPAFileName" ]]; then
    echo_tip "打包成功屹耐!"
else
    echo_error "打包失敗尸疆,請修改后重試!"
    exit 1
fi

如果一切順利惶岭,ipa包應(yīng)該就在你設(shè)置的目錄下面了仓技!

8. 最后附上完成的腳本:

#!/bin/sh

PlistBuddy=/usr/libexec/PlistBuddy

function echo_tip() {
    echo "\033[36;49m$1\033[0m"
}
function echo_error() {
    echo "\033[31;49m$1\033[0m"
}


# if [[ "$1"x != "x" ]]; then
#     project_root_path=$1
# fi

project_root_path=$(PWD -P)
project_name=""
project_type=""
scheme=""
info_plist_file_path=""
ipa_file_name=""
code_sign=""
uuid=""

ipa_file_path="$project_root_path/ipa"
configuration="Release"
provision_profile_path="$ipa_file_path/ZXIPTV_InHouse.mobileprovision"
build_path="$project_root_path/build"

# 獲取工程名稱 1: 單個(gè)工程, 2: 工作空間
function get_project_info() {
    cd $1
    workspace=`ls . | grep "xcworkspace$"`
    if [[ x"$workspace" != "x" ]]; then
        project_name=`echo $workspace | cut -d "." -f1`
        project_type="2"
        return "0"
    else
        project=`ls . | grep "xcodeproj$"`
        if [[ x"$project" != "x" ]]; then
            project_name=`echo $project | cut -d "." -f1`
            project_type="1"
            return "0"
        fi
    fi

    echo_error "目錄不是一個(gè)有效的工程目錄"
    exit 1
}

# 校驗(yàn)scheme是否正確
function validate_scheme() {
    info=`xcodebuild -list`
    schemes=${info#*Schemes:}
    for item in $schemes; do
        if [[ "$1"x == "$item"x ]]; then
            return "0"
        fi
    done

    echo "$1 is not in [$schemes]"
    exit 1
}

function validate_configuration() {
    info=`xcodebuild -list`
    configurations=${info#*Configurations:}
    configurations=${configurations%If*}
    for item in $configurations; do
        if [[ "$1"x == "$item"x ]]; then
            return "0"
        fi
    done
    exit 1
}

# 獲取指定target對應(yīng)的info.plist文件名稱, 參數(shù)為scheme值
function get_info_plist_file_path() {
    settings=`xcodebuild -showBuildSettings -scheme $1`
    str1=${settings#*PRODUCT_SETTINGS_PATH = }
    path=${str1%%.plist*}
    info_plist_file_path=$path".plist"
}

# 解析provision profile, 參數(shù)為描述文件路徑
function parse_provision_profile() {
    temp_plist_path="$ipa_file_path/temp.plist"
    if [[ -f "$temp_plist_path" ]]; then
            rm $temp_plist_path
    fi

    security cms -D -i $1 > $temp_plist_path
    code_sign_identity=`$PlistBuddy -c 'Print DeveloperCertificates:0' $temp_plist_path | \
                        openssl x509 -subject -inform der|head -n 1`
    code_sign=`echo "$code_sign_identity" | cut -d "/" -f3 | cut -d "=" -f2`
    uuid=`$PlistBuddy -c "Print UUID" $temp_plist_path`

    rm $temp_plist_path

    if [[ $code_sign == "" || $uuid == "" ]]; then
        echo_error "無法解析描述文件[$provision_profile_path]"
        exit 1
    fi
}

# 設(shè)置版本號, 參數(shù)1為version, 參數(shù)2為plist文件路徑
function update_version() {
    old_version=$($PlistBuddy -c "Print CFBundleVersion" $2)
    old_short_version=$($PlistBuddy -c "Print CFBundleShortVersionString" $2)
    echo_tip "before update, version = $old_version, short version = $old_short_version"

    short_version=$(echo $1 | cut -d "." -f 1-3)
    $PlistBuddy -c "Set:CFBundleVersion $1" "$2"
    $PlistBuddy -c "Set:CFBundleShortVersionString $short_version" "$2"
    new_version=$($PlistBuddy -c "Print CFBundleVersion" $2)
    new_short_version=$($PlistBuddy -c "Print CFBundleShortVersionString" $2)
    echo_tip "after update, version = $new_version, short version = $new_short_version"
    
    return "0"
}

#=====================================================================================

get_project_info "$project_root_path"
parse_provision_profile "$provision_profile_path"

scheme=$project_name
validate_scheme "$scheme"
validate_configuration "$configuration"
get_info_plist_file_path "$scheme"

version=`$PlistBuddy -c "Print CFBundleVersion" "$info_plist_file_path"`
if [[ "$1"x != "x" ]]; then
    version=$1
    update_version "$version" "$info_plist_file_path"
fi

ipa_file_name="$project_name-$version.ipa"

echo_tip "project_root_path = $project_root_path"
echo_tip "project_name = $project_name"
echo_tip "scheme = $scheme"
echo_tip "info_plist_file_path = $info_plist_file_path"
echo_tip "version = $version"
echo_tip "ipa_file_name = $ipa_file_name"
echo_tip "ipa_file_path = $ipa_file_path"
echo_tip "code_sign = $code_sign"
echo_tip "uuid = $uuid"

#=====================================================================================

function prepare_build() {
    rm -rf $build_path
    mkdir -p $build_path
    mkdir -p $ipa_file_path

    for path in `find "$project_root_path" -name "*.a"`; do
        cp $path $build_path
    done
}

function build() {
    if [[ "$project_type" == "1" ]]; then
        /usr/bin/xcodebuild \
            -target $scheme  \
            -configuration $configuration -sdk iphoneos \
            OBJROOT=$build_path TARGET_BUILD_DIR=$build_path LIBRARY_SEARCH_PATHS=$build_path \
            CODE_SIGN_IDENTITY="$code_sign" PROVISIONING_PROFILE="$uuid"
    else
        /usr/bin/xcodebuild \
            -workspace $project_name.xcworkspace -scheme $scheme \
            -configuration $configuration -sdk iphoneos \
            OBJROOT=$build_path TARGET_BUILD_DIR=$build_path LIBRARY_SEARCH_PATHS=$build_path \
            CODE_SIGN_IDENTITY="$code_sign" PROVISIONING_PROFILE="$uuid"
    fi

    ReturnCode=$(echo $?)
    if ([[ $ReturnCode == "0" ]] && [[ -d "$build_path/$project_name.app" ]]); then
        echo_tip "編譯成功!"
    else
        echo_error "編譯失敗,請修改后重試卦洽!"
        exit 1
    fi
}

function package() {
    # 刪除舊的ipa文件
    if [[ -f "$ipa_file_path/$ipa_file_name" ]]; then
        rm -f "$ipa_file_path/$ipa_file_name"
    fi

    /usr/bin/xcrun -sdk iphoneos \
        PackageApplication \
            -v $build_path/$project_name.app \
            -o $ipa_file_path/$ipa_file_name \
            --sign "$code_sign" \
            --embed "$provision_profile_path"

    rm -rf $TargetBuildDir

    if [[ -f "$ipa_file_path/$ipa_file_name" ]]; then
        echo_tip "打包成功寂诱!"
    else
        echo_error "打包失敗,請修改后重試牛隅!"
        exit 1
    fi
}

prepare_build
build
package

如果有任何問題,請聯(lián)系我!

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末羡亩,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子危融,更是在濱河造成了極大的恐慌畏铆,老刑警劉巖,帶你破解...
    沈念sama閱讀 206,378評論 6 481
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件吉殃,死亡現(xiàn)場離奇詭異辞居,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)蛋勺,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 88,356評論 2 382
  • 文/潘曉璐 我一進(jìn)店門瓦灶,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人抱完,你說我怎么就攤上這事贼陶。” “怎么了?”我有些...
    開封第一講書人閱讀 152,702評論 0 342
  • 文/不壞的土叔 我叫張陵碉怔,是天一觀的道長烘贴。 經(jīng)常有香客問我,道長撮胧,這世上最難降的妖魔是什么桨踪? 我笑而不...
    開封第一講書人閱讀 55,259評論 1 279
  • 正文 為了忘掉前任,我火速辦了婚禮趴樱,結(jié)果婚禮上馒闷,老公的妹妹穿的比我還像新娘。我一直安慰自己叁征,他們只是感情好纳账,可當(dāng)我...
    茶點(diǎn)故事閱讀 64,263評論 5 371
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著捺疼,像睡著了一般疏虫。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上啤呼,一...
    開封第一講書人閱讀 49,036評論 1 285
  • 那天卧秘,我揣著相機(jī)與錄音,去河邊找鬼官扣。 笑死翅敌,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的惕蹄。 我是一名探鬼主播蚯涮,決...
    沈念sama閱讀 38,349評論 3 400
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼卖陵!你這毒婦竟也來了遭顶?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 36,979評論 0 259
  • 序言:老撾萬榮一對情侶失蹤泪蔫,失蹤者是張志新(化名)和其女友劉穎棒旗,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體撩荣,經(jīng)...
    沈念sama閱讀 43,469評論 1 300
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡铣揉,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 35,938評論 2 323
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了餐曹。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片老速。...
    茶點(diǎn)故事閱讀 38,059評論 1 333
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖凸主,靈堂內(nèi)的尸體忽然破棺而出橘券,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 33,703評論 4 323
  • 正文 年R本政府宣布旁舰,位于F島的核電站锋华,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏箭窜。R本人自食惡果不足惜毯焕,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,257評論 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望磺樱。 院中可真熱鬧纳猫,春花似錦、人聲如沸竹捉。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,262評論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽块差。三九已至侵续,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間憨闰,已是汗流浹背状蜗。 一陣腳步聲響...
    開封第一講書人閱讀 31,485評論 1 262
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留鹉动,地道東北人轧坎。 一個(gè)月前我還...
    沈念sama閱讀 45,501評論 2 354
  • 正文 我出身青樓,卻偏偏與公主長得像泽示,于是被迫代替她去往敵國和親眶根。 傳聞我的和親對象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 42,792評論 2 345

推薦閱讀更多精彩內(nèi)容