
前言
Fastlane是一套使用Ruby寫的自動化工具集,目的是為了簡化Android和iOS的部署過程,自動化你的工作流。它可以簡化一些乏味、單調(diào)、重復(fù)的工作,像截圖、代碼簽名以及發(fā)布App。這里主要是為了記錄一次自己Mac環(huán)境下配置fastlane的過程。下圖是Fastlane的主要流程和功能

Fastlane文檔
安裝最新Xcode命令行工具
xcode-select --install
如果你沒有安裝,會彈出對話框,點擊安裝即可。

如果你已經(jīng)安裝過了,會有如下提示
xcode-select: error: command line tools are already installed, use "Software Update" to install updates
Fastlane安裝
sudo gem install fastlane -NV
或者
brew cask install fastlane
推薦使用RubyGems安裝。
注意??:安裝過程中可能會報錯You don't have write permissions for the /usr/bin directory.,使用如下代碼即可
sudo gem install fastlane -n /usr/local/bin

安裝完成后可以執(zhí)行fastlane -v檢查是否安裝成功.
fastlane -v

初始化Fastlane
-
cd到你的項目根目錄下fastlane init
注意??:如果你的工程是用cocoapods的那么可能會提示讓你勾選工程的Scheme;步驟就是打開你的xcode-->Manage Schemes-->Scheme-->后面的多選框中進行勾選,然后可以手動刪除 fastlane文件夾,重新fastlane init一下。

1. 幫我們自動截取APP中的截圖,并添加手機邊框(如果需要的話),我們這里不選擇這個選項,因為我們的項目已經(jīng)有圖片了,不需要這里截屏。
2. 自動發(fā)布beta版本用于TestFlight
3. 自動的App Store發(fā)布包。
4. 手動設(shè)置。
- 選擇3即可,后續(xù)會提示你輸入開發(fā)者賬號和密碼,輸入賬號雙重認證的驗證碼。


- 然后輸入你的
appName即可。 - 如果驗證碼不行,需要短信,則輸入
sms,選擇固定手機即可

- 選擇允許
fastlane管理ITC上的元數(shù)據(jù)后,會將ITC上的所有元數(shù)據(jù)與截圖下載到metadata和screenshots文件夾。

- 后面會出現(xiàn)卡住
bundle update步驟中,這是被墻的結(jié)果。

- 只需要關(guān)閉
終端,打開項目文件夾,找到fastlane init過程中生成的Gemfile文件,并打開,將https://rubygems.org,換成https://gems.ruby-china.com,然后打開終端,cd到當(dāng)前項目,輸入bundle update。

注意??:過程當(dāng)中會有很多填寫密碼或者詢問(y/n)。
-
Fastlane初始化完成后,工程根目錄下會生成fastlane文件夾,結(jié)構(gòu)如下:fastlane ├── Appfile ├── Deliverfile ├── Fastfile ├── metadata │ ├── app_icon.jpg │ ├── copyright.txt │ ├── primary_category.txt │ ├── primary_first_sub_category.txt │ ├── primary_second_sub_category.txt │ ├── review_information │ │ ├── demo_password.txt │ │ ├── demo_user.txt │ │ ├── email_address.txt │ │ ├── first_name.txt │ │ ├── last_name.txt │ │ ├── notes.txt │ │ └── phone_number.txt │ ├── secondary_category.txt │ ├── secondary_first_sub_category.txt │ ├── secondary_second_sub_category.txt │ ├── trade_representative_contact_information │ │ ├── address_line1.txt │ │ ├── address_line2.txt │ │ ├── address_line3.txt │ │ ├── city_name.txt │ │ ├── country.txt │ │ ├── email_address.txt │ │ ├── first_name.txt │ │ ├── is_displayed_on_app_store.txt │ │ ├── last_name.txt │ │ ├── phone_number.txt │ │ ├── postal_code.txt │ │ ├── state.txt │ │ └── trade_name.txt │ └── zh-Hans │ ├── description.txt │ ├── keywords.txt │ ├── marketing_url.txt │ ├── name.txt │ ├── privacy_url.txt │ ├── promotional_text.txt │ ├── release_notes.txt │ ├── subtitle.txt │ └── support_url.txt └── screenshots ├── README.txt └── zh-Hans ├── 1_iphone6Plus_1.Simulator\ Screen\ Shot\ -\ iPhone\ 8\ Plus\ -\ 2018-06-01\ at\ 17.21.05.png ├── 2_iphone6Plus_2.Simulator\ Screen\ Shot\ -\ iPhone\ 8\ Plus\ -\ 2018-06-01\ at\ 17.21.29.png ├── 3_iphone6Plus_3.Simulator\ Screen\ Shot\ -\ iPhone\ 8\ Plus\ -\ 2018-06-01\ at\ 17.29.41.png ├── 4_iphone6Plus_4.Simulator\ Screen\ Shot\ -\ iPhone\ 8\ Plus\ -\ 2018-06-01\ at\ 17.29.46.png └── 5_iphone6Plus_5.Simulator\ Screen\ Shot\ -\ iPhone\ 8\ Plus\ -\ 2018-06-01\ at\ 17.29.51.png 6 directories, 46 files
安裝所需插件
Fastlane的插件是一個或者一組action的打包,單獨發(fā)布在fastlane之外。首次安裝插件后會生成一個Pluginfile文件
#查看所有插件
fastlane search_plugins
# 安裝方法
fastlane add_plugin [name]
#常用插件
fastlane add_plugin versioning
fastlane add_plugin firim
fastlane add_plugin fir_cli # 官方版
fastlane add_plugin pgyer
#更新插件
fastlane update_plugins

插件說明
fastlane add_plugin versioning:用來修改 build 版本號和 version 版本號,fastlane 內(nèi)嵌的actionincrement_build_number使用的是蘋果提供的agvtool, 在更改Build的時候會改變所有target的版本號。如果你在一個工程里有多個target,每次編譯,所有的Build都要加1。 有了fastlane-plugin-versioning不僅可以指定target增加Build,當(dāng)然也可以直接設(shè)定Version, 并且可以指定版本號的版本(major/miner/patch)。
fastlane-plugin-pgyer:上傳到蒲公英分發(fā)平臺。
fastlane-plugin-firim:上傳到firim。
注意??:如果你需要發(fā)布到蒲公英或者firim必須提前安裝插件,否則后面會操作失敗。
Fastlane的文件配置
注意??: Fastlane是使用Ruby寫的,配置文件修改可以使用VS Code,然后下個Ruby插件這樣方便修改。

Gemfile
類似于cocopods 的Podfile文件。
Metadata
元數(shù)據(jù)文件夾,截圖文件夾,一般fastlane init的時候會自動下載下來的。
.env
配置環(huán)境變量(在fastlane init進行初始化后并不會自動生成,如果需要可以自己創(chuàng)建)。用于把賬號信息、更新描述、工程相關(guān)信息、證書文件等單獨放在一個配置文件,方便集中更改。
cd到工程目錄fastlane文件夾下:
touch .env
注意??: .env是一個隱藏文件,我們可以是command+shift+.顯示隱藏文件。另外.env可以使用VS Code編輯,但是需要安裝dotEnv插件。
#APP唯一標(biāo)識符
APP_IDENTIFIER = ""
#蘋果開發(fā)者賬號
APPLE_ID = ""
#apple developer Team ID
TEAM_ID = ""
#itunes connect Team ID
ITC_TEAM_ID = ""
#工程名稱
SCHEME_NAME = ""
#App 元數(shù)據(jù)及截圖存放路徑
METADATA_PATH = "./metadata"
SCREENSHOTS_PATH = "./screenshots"
#appicon文件夾路徑
APPICON_PATH = './fastlane/metadata/app_icon.jpg'
#ipa輸出文件夾路徑
OUTPUT_DIRECTORY = "/Users/hfk/Desktop/AlliPA/ipa"
#App 元數(shù)據(jù)及截圖下載時 直接覆蓋 不詢問
DELIER_FORCE_OVERWRITE = false
#provisioning profile配置(如果有三方登錄或者通知必須)
PP_DEVELOPMENT = ""
PP_ADHOC = ""
PP_APPSTORE = ""
#更新描述
UPDATE_DESCRIPTION = "fastlane自動打包上傳測試"
# 蒲公英 api_key user_key
PGYER_API_KEY = ''
PGYER_USER_KEY = ''
PGYER_INSTALL_TYPE = '2' #1:公開,2:密碼安裝,3:邀請安裝,4:回答問題安裝。默認為1公開
PGYER_INSTALL_PASSWORD = '123456'
# Firm token
Firm_API_Token = ''

使用方法:例如獲取工程名稱ENV['SCHEME_NAME']
Appfile
存儲有關(guān)開發(fā)者賬號相關(guān)信息,app_identifier, apple_id, team_id, itc_team_id等一些fastlane需要用到的信息。一般在fastlane init的時候會初始化出來,如果沒有就需要自己添加。
app_identifier ENV['APP_IDENTIFIER'] # The bundle identifier of your app
apple_id ENV['APPLE_ID'] # Your Apple email address
itc_team_id ENV['ITC_TEAM_ID'] # App Store Connect Team ID
team_id ENV['TEAM_ID'] # Developer Portal Team ID
# For more information about the Appfile, see:
# https://docs.fastlane.tools/advanced/#appfile
Deliverfile
工具的配置文件,metadata 文件夾中的文件比較多且雜,僅一個屬性的配置卻使用一個單獨的.txt文件來存儲,官方文檔表示可以使用Deliverfile文件來配置且優(yōu)先級高于matadata 中.txt文件中的配置。
# The Deliverfile allows you to store various App Store Connect metadata
# For more information, check out the docs
# https://docs.fastlane.tools/actions/deliver/
############################# 基本信息 ####################################
# bundle identifier
app_identifier ENV['APP_IDENTIFIER']
# Apple ID用戶名
username ENV['APPLE_ID']
# 版權(quán)聲明
# copyright "2020 xxx Inc"
# 支持語言
supportedLanguages = {
"cmn-Hans" => "zh-Hans"
}
# app 名稱
# name({
# 'zh-Hans' => "APPName"
# })
# 副標(biāo)題
# subtitle(
# 'zh-Hans' => "副標(biāo)題"
# )
# App價格
#price_tier 0
# 應(yīng)用程序圖標(biāo)的路徑 1024*1024
app_icon './fastlane/metadata/app_icon.jpg'
# 屏幕截圖的文件夾的路徑
screenshots_path ENV['SCREENSHOTS_PATH']
# 元數(shù)據(jù)的路徑
metadata_path ENV['METADATA_PATH']
################################### 類別配置 ###################################
# 參考網(wǎng)站https://docs.fastlane.tools/actions/upload_to_app_store/#reference
# 設(shè)置 App 的類別.這里可以設(shè)置一個主要類別,一個次要類別.
# 主要類別
primary_category "MZGenre.Lifestyle"
# 主要類別第一個子類別 無
# primary_first_sub_category
# 主要類別第二個子類別 無
# primary_second_sub_category
# 要設(shè)置的次要類別
secondary_category "MZGenre.Utilities"
# 設(shè)置的次要第一個子類別 無
# secondary_first_sub_category
# 設(shè)置的次要第二個子類別 無
# secondary_second_sub_category
################################## 關(guān)鍵字\描述等信息 ###################################
# 搜索關(guān)鍵字
# keywords(
# "zh-Hans" => "FastLane"
# )
# 技術(shù)支持網(wǎng)址
# support_url({
# 'zh-Hans' => "http://www.baidu.com"
# })
# 營銷網(wǎng)址
#marketing_url({
# 'zh-Hans' => "http://www.baidu.com"
#})
# 隱私政策網(wǎng)址
#privacy_url({
# 'zh-Hans' => "http://www.baidu.com"
#})
# 本地化宣傳文本信息介紹
#promotional_text(
# "zh-Hans" => "本地化宣傳文本信息介紹",
#)
# app描述信息
#description({
# 'zh-Hans' => "APP的描述信息,用于APP功能的描述和介紹不能少于10個字符"
#})
# 版本描述
#release_notes({
# 'zh-Hans' => "這是第一個版本哦"
#})
################################## 分級 ########################################
#年齡分級配置
#app_rating_config_path "./fastlane/metadata/itunes_rating_config.json"
################################# 提交審核信息等 #########################################
# 提交審核信息:加密, idfa 等
submission_information({
export_compliance_encryption_updated: false,
export_compliance_uses_encryption: false,
content_rights_contains_third_party_content: false,
add_id_info_uses_idfa: false,
add_id_info_serves_ads: true,
add_id_info_limits_tracking: true
})
# # 應(yīng)用審核小組的聯(lián)系信息 app 審核信息
# app_review_information(
# first_name: "name",
# last_name: "name",
# phone_number: "手機號",
# email_address: "email",
# demo_user: "測試賬號用戶名",
# demo_password: "測試賬號密碼",
# notes: "noting"
# )
# run_precheck_before_submit true
# 在上傳新截圖之前,先清除所有之前上傳的截圖
overwrite_screenshots true
# 下載 metadata 及 screenshots 時直接覆蓋,不詢問
force true
# 不上傳截圖
skip_screenshots true
# 是否自動提交審核,true表示立馬提交審核
submit_for_review false
# 審核通過后是否立刻發(fā)布,false表示需要手動發(fā)布
automatic_release true
Fastfile
核心文件,主要用于命令行調(diào)用和處理具體的流程,lane相對于一個方法或者函數(shù)。
# This file contains the fastlane.tools configuration
# You can find the documentation at https://docs.fastlane.tools
#
# For a list of all available actions, check out
#
# https://docs.fastlane.tools/actions
#
# For a list of all available plugins, check out
#
# https://docs.fastlane.tools/plugins/available-plugins
#
# Uncomment the line if you want fastlane to automatically update itself
# update_fastlane
default_platform(:ios)
# 定義全局參數(shù) 大寫開頭為常數(shù),小寫、_開頭為變量,$開頭為全局變量(直接用#訪問)
# 超時時間
ENV["FASTLANE_XCODEBUILD_SETTINGS_TIMEOUT"] = "180"
# 嘗試次數(shù)
ENV["FASTLANE_XCODEBUILD_SETTINGS_RETRIES"] = "10"
# scheme名
SCHEME_NAME = ENV['SCHEME_NAME']
# workspace名
WORKSPACE_NAME = "#{SCHEME_NAME}.xcworkspace"
# plist文件路徑
INFO_PLIST_PATH = "#{SCHEME_NAME}/Info.plist"
# 版本號
$VERSION_NUMBER = ""
# 構(gòu)建版本號
$BUILD_NUMBER = ""
# ipa導(dǎo)出路徑
$OUTPUT_DIRECTORY = ENV['OUTPUT_DIRECTORY']
# ipa安裝包路徑
$IPA_PATH = ""
# 是否準備完成
$PREPARE_COMPLETED = false
platform :ios do
before_all do
# 所有l(wèi)ane執(zhí)行之前
# 使用環(huán)境變量提供這個密碼給fastlane,解決雙重認證生成的特殊密碼
ENV["FASTLANE_APPLE_APPLICATION_SPECIFIC_PASSWORD"] = "xxx"
# ENV["SLACK_URL"] = "https://hooks.slack.com/services/..."
# 拉取遠程最新代碼
# git_pull
# 執(zhí)行 pod instasll
# cocoapods
# carthage
end
desc '打包前的準備工作'
lane :prepare do |options|
if !$PREPARE_COMPLETED
puts "\033[32m====================即將開始打包====================\033[0m\n"
puts '您好,即將為你自動打包'
end
export_method = options[:export_method]
select_method = '-1'
# => 如果沒有選擇打包方式,提示選擇打包方式
if export_method.nil? || export_method.empty?
puts "請選擇打包方式 \033[33m1:打包上傳AppStore(默認) 2:打包Development上傳蒲公英Firm 3:打包AdHoc上傳蒲公英Firm 4:打包Inhouse上傳蒲公英Firm 0:結(jié)束打包 回車表示使用默認打包\033[0m"
select_method = STDIN.gets.chomp
if select_method!='1' && select_method!='2' && select_method!='3' && select_method!='4' && !select_method.empty?
# supported [:select, :message, :verbose, :error, :password, :input, :success, :important, :command, :user_error!, :command_output, :deprecated, :header, :content_error, :interactive?, :confirm, :crash!, :not_implemented, :shell_error!, :build_failure!, :test_failure!, :abort_with_message!]
UI.user_error!("您已取消打包 ??")
end
end
if !$PREPARE_COMPLETED
currentVersion = get_info_plist_value(path: "#{INFO_PLIST_PATH}", key: "CFBundleShortVersionString")
currentBuild = get_info_plist_value(path: "#{INFO_PLIST_PATH}", key: "CFBundleVersion")
puts "當(dāng)前工程的版本號是:\033[33m#{currentVersion}\033[0m 構(gòu)建版本號是:\033[33m#{currentBuild}\033[0m"
version = options[:version]
build = options[:build]
output_directory = options[:output_directory]
# => 如果沒有選擇版本號,提示是否需要輸入版本號
if version.nil? || version.empty?
puts "請輸入版本號,回車表示使用當(dāng)前版本號\033[33m#{currentVersion}\033[0m"
version = STDIN.gets.chomp
if version == '' # 回車
$VERSION_NUMBER = currentVersion
else
$VERSION_NUMBER = version
end
else
$VERSION_NUMBER = version
end
# => 如果沒有選擇構(gòu)建版本號,提示是否需要輸入構(gòu)建版本號
if build.nil? || build.empty?
puts "請輸入構(gòu)建版本號,回車表示使用默認自動生成構(gòu)建版本號"
build = STDIN.gets.chomp
if build == '' # 回車
# $BUILD_NUMBER = AUTO_BUILD_NUMBER
else
$BUILD_NUMBER = build
end
else
$BUILD_NUMBER = build
end
# => 如果沒有選擇ipa輸出目錄,提示是否需要輸入打包路徑
if output_directory.nil? || output_directory.empty?
puts "請指定ipa包輸出路徑,回車表示使用默認輸出路徑:\033[33m#$OUTPUT_DIRECTORY\033[0m"
output_directory = STDIN.gets.chomp
if output_directory == '' # 回車
else
$OUTPUT_DIRECTORY = output_directory
end
else
$OUTPUT_DIRECTORY = output_directory
end
end
$PREPARE_COMPLETED = true
if select_method != '-1' # 已選擇
case select_method
when '1'
# 發(fā)布到appstore
release_appstore(options)
when '2'
# 打包Development或Adhoc發(fā)布到蒲公英Firm
release_development(options)
when '3'
# 打包Adhoc發(fā)布到蒲公英Firm
release_adhoc(options)
when '4'
# 打包inhouse發(fā)布到蒲公英
release_enterprise(options)
end
next
end
# => 詳細信息
summary(options)
end
desc "信息確認"
lane :summary do |options|
puts "\033[32m====================信息確認====================\033[0m\n"
puts "您設(shè)置的包輸出路徑為:"
# supported [:select, :message, :verbose, :error, :password, :input, :success, :important, :command, :user_error!, :command_output, :deprecated, :header, :content_error, :interactive?, :confirm, :crash!, :not_implemented, :shell_error!, :build_failure!, :test_failure!, :abort_with_message!]
UI.important "#$OUTPUT_DIRECTORY"
puts "您選擇的打包方式為:"
UI.important "#{options[:export_method]}"
puts "指定的發(fā)布版本號為:"
UI.important "#$VERSION_NUMBER"
confirm = UI.confirm "確認信息是否正確,輸入y繼續(xù)打包"
if !confirm
UI.user_error!("您已取消打包 ??")
end
puts "\033[32m====================信息確認====================\033[0m\n"
puts "3s后開始自動打包..."
sleep(3)
end
desc "更新版本號"
lane :update_version do
puts("*************| 更新version #$VERSION_NUMBER |*************")
increment_version_number_in_plist(
target: SCHEME_NAME,
version_number: $VERSION_NUMBER
)
puts("*************| 更新build #$BUILD_NUMBER |*************")
increment_build_number_in_plist(
target: SCHEME_NAME,
build_number: $BUILD_NUMBER
)
end
desc "打包發(fā)布"
lane :release do |options|
prepare(options)
end
desc "發(fā)布到appstore"
lane :release_appstore do |options|
options[:export_method] = "app-store"
prepare(options)
build(options)
deliver_appstore
end
desc "發(fā)布development"
lane :release_development do |options|
options[:export_method] = "development"
prepare(options)
build(options)
deliver_pgyer
deliver_firm
end
desc "發(fā)布ad-hoc"
lane :release_adhoc do |options|
options[:export_method] = "ad-hoc"
prepare(options)
build(options)
deliver_pgyer
deliver_firm
end
desc "發(fā)布企業(yè)Inhouse"
lane :release_enterprise do |options|
options[:export_method] = "enterprise"
prepare(options)
build(options)
deliver_pgyer
deliver_firm
end
desc "上傳到蒲公英"
lane :deliver_pgyer do |options|
pgyer(
api_key: ENV['PGYER_API_KEY'], # 從蒲公英項目詳情中獲取的apikey
user_key: ENV['PGYER_USER_KEY'], # 從蒲公英項目詳情中獲取的 userkey
#apk: $APK_PATH, #apk包路徑
ipa: $IPA_PATH, #ipa包路徑
install_type: ENV['PGYER_INSTALL_TYPE'], #1:公開,2:密碼安裝,3:邀請安裝,4:回答問題安裝。默認為1公開
password: ENV['PGYER_INSTALL_PASSWORD'], #設(shè)置安裝密碼
update_description: ENV['UPDATE_DESCRIPTION'] #更新描述
)
end
desc "上傳到Firm"
lane :deliver_firm do |options|
firim(
firim_api_token: ENV['Firm_API_Token'], # 從Firm項目詳情中獲取的apitoken
ipa: $IPA_PATH, #ipa包路徑
icon: ENV['APPICON_PATH'] #icon
)
# fir_cli( #官方版
# api_token: ENV['Firm_API_Token'], # 從Firm項目詳情中獲取的apitoken
# specify_file_path: $IPA_PATH, #ipa包路徑
# specify_icon_file: ENV['APPICON_PATH'] #icon
# changelog: ENV['UPDATE_DESCRIPTION'] #更新描述
# )
end
desc "上傳到appstore"
lane :deliver_appstore do |options|
deliver(
username: ENV['APPLE_ID'], # 開發(fā)者賬號
team_id: ENV['ITC_TEAM_ID'], # ITC Team ID
dev_portal_team_id: ENV['TEAM_ID'], # ADC Team ID
app_identifier: ENV['APP_IDENTIFIER'], # bundle ID
ipa: $IPA_PATH, # ipa包路徑
app_version: $VERSION_NUMBER, # 更新版本號
release_notes: {
'zh-Hans' => "這是第一個版本哦"
},
submit_for_review: false,# 是否自動提交審核,true表示立馬提交審核
automatic_release: true,# 審核通過后是否立刻發(fā)布,false表示需要手動發(fā)布
force: true, # 設(shè)置true,會跳過預(yù)覽頁面,直接上架
skip_screenshots: true, # 不上傳截圖
skip_metadata: true, # 不上傳元數(shù)據(jù)
)
end
desc "打包"
lane :build do |options|
# gym用來編譯ipa
# 編譯時間
build_time = Time.now.strftime("%Y-%m-%d %H-%M-%S")
# 自動生成的build版本號
auto_build_number = Time.now.strftime("%Y%m%d%H%M%S")
if $BUILD_NUMBER.empty?
$BUILD_NUMBER = auto_build_number
end
# 更新版本號
update_version
# 獲取打包方式
export_method = options[:export_method]
# 配置項
configuration = 'Release'
# pp文件
provisioningProfiles = ENV['PP_APPSTORE']
# 輸出目錄
outputDir = ''
# 輸出文件名
outputName = "#{SCHEME_NAME}_#$VERSION_NUMBER_#$BUILD_NUMBER_#{export_method}.ipa"
case export_method
when 'development'
configuration = 'Debug'
outputDir = "#$OUTPUT_DIRECTORY/Development/#{SCHEME_NAME}-#{build_time}"
when 'app-store'
outputDir = "#$OUTPUT_DIRECTORY/Appstore/#{SCHEME_NAME}-#{build_time}"
when 'ad-hoc'
provisioningProfiles = ENV['PP_ADHOC']
outputDir = "#$OUTPUT_DIRECTORY/ADHOC/#{SCHEME_NAME}-#{build_time}"
when 'enterprise'
provisioningProfiles = ENV['PP_ENTERPRISE']
outputDir = "#$OUTPUT_DIRECTORY/ADHOC/#{SCHEME_NAME}-#{build_time}"
end
$IPA_PATH = gym(
clean: 'true', # 在打包前是否先執(zhí)行clean。
scheme: "#{SCHEME_NAME}", # 指定項目的scheme名稱
workspace: "#{WORKSPACE_NAME}", # 指定.xcworkspace文件的路徑。
configuration: "#{configuration}", # 指定打包時的配置項,默認為Release
output_name: "#{outputName}", # 指定生成的.ipa文件的名稱,應(yīng)包含文件擴展名。
output_directory: "#{outputDir}", # 指定.ipa文件的輸出目錄
include_symbols: 'true', # 是否導(dǎo)出符號表
# include_bitcode: 'false', # 是否使用bitcode打包
export_xcargs: "-allowProvisioningUpdates", #訪問鑰匙串
silent: true, # 是否隱藏打包時不需要的信息。
buildlog_path: "#{outputDir}", # 指定編譯日志文件的輸出目錄
export_options: {
method: "#{export_method}", # 指定導(dǎo)出.ipa時使用的方法,可用選項:app-store,ad-hoc,enterprise,development
thinning: "<none>", # 是否瘦身
#provisioningProfiles: { //如果有三方登錄或者通知必須放開
# "#{ENV['APP_IDENTIFIER']}" => "#{provisioningProfiles}"
# }
}
)
end
after_all do |lane|
# 在macOS 通知欄發(fā)送通知
notification(subtitle: "Successfully", message: "Successfully deployed new App Update")
#slack(
# message: "Successfully deployed new App Update."
#)
end
error do |lane, exception|
#slack(
# message: exception.message,
# success: false
#)
end
# 釘釘機器人
desc "dingdingTalk"
lane :dingdingTalk do |options|
app_url = "https://www.pgyer.com/xxxx"
app_qrurl = "https://www.pgyer.com/app/qrcode/xxxx"
if $UPDATE_DESCRIPTION == "測試版"
app_url = "https://www.pgyer.com/xxxx"
app_qrurl = "https://www.pgyer.com/app/qrcode/xxxx"
end
curl = %Q{
curl 'Webhook' \
-H 'Content-Type:application/json' \
-d '{
"msgtype":"markdown",
"markdown":{
"title":"#{$UPDATE_DESCRIPTION}更新成功!??",
"text":"### #{$UPDATE_DESCRIPTION}更新成功!?? \n [@xxxx](#{app_url}) \n\n [#{app_url}](#{app_url})\n\n **掃碼安裝↓↓↓**\n\n [圖片上傳失敗...(image-471666-1662695255072)]\n"
},
"at": {
"atMobiles": [
"xxxx",
],
"isAtAll": false
},
}'
}
system curl
end
end
注意??: 在text里添加@人的手機號,且只有在群內(nèi)的成員才可被@,非群內(nèi)成員手機號會被脫敏。
Fastlane發(fā)布
cd到工程目錄下,調(diào)用fastlane release,之后根據(jù)提示選擇需要的過程即可完成發(fā)布。
注意??: 如果出現(xiàn)如下錯誤,就去工程中Edit Scheme --> 勾中Shared
Couldn't find specified scheme 'YourScheme'. Please make sure that the scheme is shared, see ...

兩步驗證問題
現(xiàn)在大部分Apple Id都開啟了兩步驗證,當(dāng)我們提交TestFilght或者AppStore的時候會提示我們輸入6位code,這樣就違背全自動發(fā)布的初衷了。
Two Factor Authentication for account 'xxxxx@xx.com' is enabled
If you're running this in a non-interactive session (e.g. server or CI)
check out https://github.com/fastlane/fastlane/tree/master/spaceship#2-step-verification
Please enter the 6 digit code:
解決辦法:
步驟:
1.訪問 https://appleid.apple.com/account/manage
2.生成一個 APP-SPECIFIC PASSWORDS,保留生成的特殊密碼,記作 A
3.使用環(huán)境變量提供這個密碼給fastlane: FASTLANE_APPLE_APPLICATION_SPECIFIC_PASSWORD
4.執(zhí)行 fastlane spaceauth -u user@email.com,生成 session cookie,記作 B。
5.通過環(huán)境變量 FASTLANE_SESSION 提供 session cookies。
配置:
方式1:
前往文件 ~/.bash_profile 中,新增并配置配置 FASTLANE_APPLE_APPLICATION_SPECIFIC_PASSWORD 和 FASTLANE_SESSION
例:(A和B就是上面生成的)
export FASTLANE_APPLE_APPLICATION_SPECIFIC_PASSWORD = A
export FASTLANE_SESSION = B
/*----------------------------------------------------*/
方式2:
ENV["FASTLANE_APPLE_APPLICATION_SPECIFIC_PASSWORD"] = "xxxxxx"
這個和環(huán)境變量配置是一個意思,但是涉及密碼寫在配置文件里面
注意??: .bash_profile文件是隱藏文件,可以使用command+shift+.控制顯示

生命周期
| 執(zhí)行順序 | 方法名 | 說明 |
|---|---|---|
| 1 | before_all | 在執(zhí)行lane之前操作,只執(zhí)行一次,比如使用cocopods更新 pod 庫 |
| 2 | before_each | 每次執(zhí)行lane之前都會執(zhí)行一次 |
| 3 | lane | 用戶自定義的任務(wù)流程,例如打包,上傳等 |
| 4 | after_each | 每次執(zhí)行lane之后都會執(zhí)行一次 |
| 5 | after_all | 在執(zhí)行所有lane成功結(jié)束之后執(zhí)行一次,例發(fā)送郵件,通知 |
| 6 | error | 在執(zhí)行上述情況任意環(huán)境報錯都會中止并執(zhí)行一次 |
fastlane常用工具
| 工具 | 描述 |
|---|---|
| scan | 自動運行測試工具,并且可以生成漂亮的HTML報告 |
| cert | 自動創(chuàng)建和管理iOS簽名證書Certificates
|
| sign | 創(chuàng)建、更新、下載、修復(fù)Provisioning Profiles的工具 |
| pem | 自動生成、更新推送配置文件 |
| match | 一個新的自動創(chuàng)建和管理iOS簽名證書和Provisioning Profiles工具(一般團隊使用) |
| snapshot | 用UI test功能實現(xiàn)自動化截圖 |
| frameit | 給截屏套上一層外邊框 |
| gym | 編譯打包生成ipa文件,又名build_ios_app或build_app
|
| produce | 如果你的產(chǎn)品還沒在iTC或者ADC建立,produce可以自動幫你完成這些工作 |
| deliver | 自動上傳截圖,APP的元數(shù)據(jù),二進制ipa文件到iTC
|
| notification | 在Mac上面顯示通知 |
多Target或者多個Scheme的可以參照一下Fastfile
# This file contains the fastlane.tools configuration
# You can find the documentation at https://docs.fastlane.tools
#
# For a list of all available actions, check out
#
# https://docs.fastlane.tools/actions
#
# For a list of all available plugins, check out
#
# https://docs.fastlane.tools/plugins/available-plugins
#
# Uncomment the line if you want fastlane to automatically update itself
# update_fastlane
default_platform(:ios)
# 定義全局參數(shù) 大寫開頭為常數(shù),小寫、_開頭為變量,$開頭為全局變量(直接用#訪問)
# 超時時間
ENV["FASTLANE_XCODEBUILD_SETTINGS_TIMEOUT"] = "180"
# 嘗試次數(shù)
ENV["FASTLANE_XCODEBUILD_SETTINGS_RETRIES"] = "10"
# target名
TARGET_NAME = ENV['TARGET_NAME']
# workspace名
WORKSPACE_NAME = "#{ENV['WORKSPACE_NAME']}.xcworkspace"
# plist文件路徑
INFO_PLIST_PATH = "#{TARGET_NAME}/Info.plist"
# bundleid
$APP_BUNDLEID = ENV["APP_BUNDLEID"]
# provisioningProfiles
$PROVISIONINGPROFILE = ""
# scheme名
$SCHEME_NAME = ""
# configuration
$CONFIGURATION = 'Release'
# APPICON_PATH
$APPICON_PATH = ENV["APPICON_PATH"]
# update description
$UPDATE_DESCRIPTION = "正式"
# 版本號
$VERSION_NUMBER = ""
# 構(gòu)建版本號
$BUILD_NUMBER = ""
# ipa導(dǎo)出路徑
$OUTPUT_DIRECTORY = ENV['OUTPUT_DIRECTORY']
# ipa安裝包路徑
$IPA_PATH = ""
# 是否準備完成
$PREPARE_COMPLETED = false
platform :ios do
before_all do
# 所有l(wèi)ane執(zhí)行之前
# 使用環(huán)境變量提供這個密碼給fastlane,解決雙重認證生成的特殊密碼
ENV["FASTLANE_APPLE_APPLICATION_SPECIFIC_PASSWORD"] = "xxx"
# ENV["SLACK_URL"] = "https://hooks.slack.com/services/..."
# 拉取遠程最新代碼
# git_pull
# 執(zhí)行 pod instasll
# cocoapods
# carthage
end
desc '打包前的準備工作'
lane :prepare do |options|
if !$PREPARE_COMPLETED
puts "\033[32m====================即將開始打包====================\033[0m\n"
puts '您好,即將為你自動打包'
end
if $SCHEME_NAME == ""
puts "請選擇打包SCHEME \033[33m1:打包test 2:打包preOnline 3:online 0:結(jié)束打包 \033[0m"
select_method = STDIN.gets.chomp
if select_method == '1'
$APP_BUNDLEID = ENV["APP_BUNDLEIDTEST"]
$SCHEME_NAME = ENV['SCHEME_NAME_TEST']
$APPICON_PATH = ENV["APPICON_PATH_TEST"]
$CONFIGURATION = 'Test_Debug'
$UPDATE_DESCRIPTION = "測試"
elsif select_method == '2'
$APP_BUNDLEID = ENV["APP_BUNDLEID"]
$SCHEME_NAME = ENV['SCHEME_NAME_PRE']
$APPICON_PATH = ENV["APPICON_PATH_PRE"]
$CONFIGURATION = 'PreOnline_Release'
$UPDATE_DESCRIPTION = "預(yù)發(fā)"
elsif select_method == '3'
$APP_BUNDLEID = ENV["APP_BUNDLEID"]
$SCHEME_NAME = ENV['SCHEME_NAME']
$APPICON_PATH = ENV["APPICON_PATH"]
$CONFIGURATION = 'Release'
$UPDATE_DESCRIPTION = "正式"
else
UI.user_error!("您已取消打包 ??")
end
end
export_method = options[:export_method]
select_method = '-1'
# => 如果沒有選擇打包方式,提示選擇打包方式
if export_method.nil? || export_method.empty?
if $SCHEME_NAME == ENV['SCHEME_NAME']
puts "請選擇打包方式 \033[33m1:打包上傳AppStore(默認) 2:打包AdHoc上傳蒲公英Firm 0:結(jié)束打包 \033[0m"
select_method = STDIN.gets.chomp
if select_method!='1' && select_method!='2'
# supported [:select, :message, :verbose, :error, :password, :input, :success, :important, :command, :user_error!, :command_output, :deprecated, :header, :content_error, :interactive?, :confirm, :crash!, :not_implemented, :shell_error!, :build_failure!, :test_failure!, :abort_with_message!]
UI.user_error!("您已取消打包 ??")
end
else
puts "請選擇打包方式 \033[33m1:打包AdHoc上傳蒲公英Firm 0:結(jié)束打包 \033[0m"
select_method = STDIN.gets.chomp
if select_method == '1'
select_method = '2'
else
UI.user_error!("您已取消打包 ??")
end
end
end
if !$PREPARE_COMPLETED
currentVersion = get_info_plist_value(path: "#{INFO_PLIST_PATH}", key: "CFBundleShortVersionString")
currentBuild = get_info_plist_value(path: "#{INFO_PLIST_PATH}", key: "CFBundleVersion")
puts "當(dāng)前工程的版本號是:\033[33m#{currentVersion}\033[0m 構(gòu)建版本號是:\033[33m#{currentBuild}\033[0m"
version = options[:version]
build = options[:build]
output_directory = options[:output_directory]
# => 如果沒有選擇版本號,提示是否需要輸入版本號
if version.nil? || version.empty?
puts "請輸入版本號,回車表示使用當(dāng)前版本號\033[33m#{currentVersion}\033[0m"
version = STDIN.gets.chomp
if version == '' # 回車
$VERSION_NUMBER = currentVersion
else
$VERSION_NUMBER = version
end
else
$VERSION_NUMBER = version
end
# => 如果沒有選擇構(gòu)建版本號,提示是否需要輸入構(gòu)建版本號
if build.nil? || build.empty?
puts "請輸入構(gòu)建版本號,回車表示使用默認自動生成構(gòu)建版本號"
build = STDIN.gets.chomp
if build == '' # 回車
# $BUILD_NUMBER = AUTO_BUILD_NUMBER
else
$BUILD_NUMBER = build
end
else
$BUILD_NUMBER = build
end
# => 如果沒有選擇ipa輸出目錄,提示是否需要輸入打包路徑
if output_directory.nil? || output_directory.empty?
puts "請指定ipa包輸出路徑,回車表示使用默認輸出路徑:\033[33m#$OUTPUT_DIRECTORY\033[0m"
output_directory = STDIN.gets.chomp
if output_directory == '' # 回車
else
$OUTPUT_DIRECTORY = output_directory
end
else
$OUTPUT_DIRECTORY = output_directory
end
end
$PREPARE_COMPLETED = true
if select_method != '-1' # 已選擇
case select_method
when '1'
# 發(fā)布到appstore
release_appstore(options)
when '2'
# 打包Adhoc發(fā)布到蒲公英Firm
release_adhoc(options)
end
next
end
# => 詳細信息
summary(options)
end
desc "信息確認"
lane :summary do |options|
puts "\033[32m====================信息確認====================\033[0m\n"
puts "您設(shè)置的包輸出路徑為:"
# supported [:select, :message, :verbose, :error, :password, :input, :success, :important, :command, :user_error!, :command_output, :deprecated, :header, :content_error, :interactive?, :confirm, :crash!, :not_implemented, :shell_error!, :build_failure!, :test_failure!, :abort_with_message!]
UI.important "#$OUTPUT_DIRECTORY"
puts "您選擇的打包SCHEME為:"
UI.important "#$SCHEME_NAME"
puts "您選擇的打包方式為:"
UI.important "#{options[:export_method]}"
puts "指定的發(fā)布版本號為:"
UI.important "#$VERSION_NUMBER"
confirm = UI.confirm "確認信息是否正確,輸入y繼續(xù)打包"
if !confirm
UI.user_error!("您已取消打包 ??")
end
puts "\033[32m====================信息確認====================\033[0m\n"
puts "3s后開始自動打包..."
sleep(3)
end
desc "更新版本號"
lane :update_version do
puts("*************| 更新version #$VERSION_NUMBER |*************")
increment_version_number_in_plist(
target: TARGET_NAME,
version_number: $VERSION_NUMBER
)
puts("*************| 更新build #$BUILD_NUMBER |*************")
increment_build_number_in_plist(
target: TARGET_NAME,
build_number: $BUILD_NUMBER
)
end
desc "打包發(fā)布"
lane :release do |options|
prepare(options)
end
desc "發(fā)布到appstore"
lane :release_appstore do |options|
options[:export_method] = "app-store"
prepare(options)
build(options)
deliver_appstore
end
desc "發(fā)布ad-hoc"
lane :release_adhoc do |options|
options[:export_method] = "ad-hoc"
prepare(options)
build(options)
deliver_pgyer
deliver_firm
end
desc "上傳到蒲公英"
lane :deliver_pgyer do |options|
pgyer(
api_key: ENV['PGYER_API_KEY'], # 從蒲公英項目詳情中獲取的apikey
#apk: $APK_PATH, #apk包路徑
ipa: $IPA_PATH, #ipa包路徑
install_type: ENV['PGYER_INSTALL_TYPE'], #1:公開,2:密碼安裝,3:邀請安裝,4:回答問題安裝。默認為1公開
password: ENV['PGYER_INSTALL_PASSWORD'], #設(shè)置安裝密碼
update_description: $UPDATE_DESCRIPTION #更新描述
)
end
desc "上傳到Firm"
lane :deliver_firm do |options|
# firim(
# firim_api_token: ENV['Firm_API_Token'], # 從Firm項目詳情中獲取的apitoken
# ipa: $IPA_PATH, #ipa包路徑
# #icon: ENV['APPICON_PATH'], #icon
# app_desc: $UPDATE_DESCRIPTION #更新描述
# )
fir_cli(
api_token: ENV['Firm_API_Token'], # 從Firm項目詳情中獲取的apitoken
specify_file_path: $IPA_PATH, #ipa包路徑
specify_icon_file: $APPICON_PATH, #icon
changelog: $UPDATE_DESCRIPTION #更新描述
)
end
desc "上傳到appstore"
lane :deliver_appstore do |options|
deliver(
username: ENV['APPLE_ID'], # 開發(fā)者賬號
team_id: ENV['ITC_TEAM_ID'], # ITC Team ID
dev_portal_team_id: ENV['TEAM_ID'], # ADC Team ID
app_identifier: $APP_BUNDLEID, # bundle ID
ipa: $IPA_PATH, # ipa包路徑
app_version: $VERSION_NUMBER, # 更新版本號
release_notes: {
'zh-Hans' => "這是第一個版本哦"
},
submit_for_review: false,# 是否自動提交審核,true表示立馬提交審核
automatic_release: true,# 審核通過后是否立刻發(fā)布,false表示需要手動發(fā)布
force: true, # 設(shè)置true,會跳過預(yù)覽頁面,直接上架
skip_screenshots: true, # 不上傳截圖
skip_metadata: true, # 不上傳元數(shù)據(jù)
)
end
desc "打包"
lane :build do |options|
# gym用來編譯ipa
# 編譯時間
build_time = Time.now.strftime("%Y-%m-%d %H-%M-%S")
# 自動生成的build版本號
auto_build_number = Time.now.strftime("%Y%m%d%H%M%S")
if $BUILD_NUMBER.empty?
$BUILD_NUMBER = auto_build_number
end
# 更新版本號
update_version
# 獲取打包方式
export_method = options[:export_method]
# pp文件
provisioningProfiles = ENV['PP_APPSTORE']
# 輸出目錄
outputDir = ''
# 輸出文件名
outputName = "#{$SCHEME_NAME}_#$VERSION_NUMBER_#$BUILD_NUMBER_#{export_method}.ipa"
case export_method
when 'app-store'
provisioningProfiles = ENV['PP_APPSTORE']
outputDir = "#$OUTPUT_DIRECTORY/Appstore/#{$SCHEME_NAME}-#{build_time}"
when 'ad-hoc'
provisioningProfiles = ENV['PP_ADHOC']
outputDir = "#$OUTPUT_DIRECTORY/ADHOC/#{$SCHEME_NAME}-#{build_time}"
end
$IPA_PATH = gym(
clean: 'true', # 在打包前是否先執(zhí)行clean。
scheme: "#{$SCHEME_NAME}", # 指定項目的scheme名稱
workspace: "#{WORKSPACE_NAME}", # 指定.xcworkspace文件的路徑。
configuration: "#{$CONFIGURATION}", # 指定打包時的配置項,默認為Release
output_name: "#{outputName}", # 指定生成的.ipa文件的名稱,應(yīng)包含文件擴展名。
output_directory: "#{outputDir}", # 指定.ipa文件的輸出目錄
include_symbols: 'true', # 是否導(dǎo)出符號表
# include_bitcode: 'false', # 是否使用bitcode打包
export_xcargs: "-allowProvisioningUpdates", #訪問鑰匙串
silent: true, # 是否隱藏打包時不需要的信息。
buildlog_path: "#{outputDir}", # 指定編譯日志文件的輸出目錄
export_options: {
method: "#{export_method}", # 指定導(dǎo)出.ipa時使用的方法,可用選項:app-store,ad-hoc
thinning: "<none>", # 是否瘦身
# provisioningProfiles: {
# "#{$APP_BUNDLEID}" => "#{"yxt_adhoc_test"}"
# }
}
)
end
after_all do |lane|
# 在macOS 通知欄發(fā)送通知
notification(subtitle: "Successfully", message: "Successfully deployed new App Update")
dingdingTalk
#slack(
# message: "Successfully deployed new App Update."
#)
end
error do |lane, exception|
#slack(
# message: exception.message,
# success: false
#)
end
# 釘釘機器人
desc "dingdingTalk"
lane :dingdingTalk do |options|
app_url = "https://www.pgyer.com/xxxx"
app_qrurl = "https://www.pgyer.com/app/qrcode/xxxx"
if $UPDATE_DESCRIPTION == "測試版"
app_url = "https://www.pgyer.com/xxxx"
app_qrurl = "https://www.pgyer.com/app/qrcode/xxxx"
end
curl = %Q{
curl 'Webhook' \
-H 'Content-Type:application/json' \
-d '{
"msgtype":"markdown",
"markdown":{
"title":"#{$UPDATE_DESCRIPTION}更新成功!??",
"text":"### #{$UPDATE_DESCRIPTION}更新成功!?? \n [@xxxx](#{app_url}) \n\n [#{app_url}](#{app_url})\n\n **掃碼安裝↓↓↓**\n\n [圖片上傳失敗...(image-84a177-1662695255072)]\n"
},
"at": {
"atMobiles": [
"xxxx",
],
"isAtAll": false
},
}'
}
system curl
end
end
問題:xcodebuild超時導(dǎo)致gym報錯修復(fù)
錯誤信息
[17:49:08]: xcodebuild -showBuildSettings timed out after 4 retries with a base timeout of 3. You can override the base timeout value with the environment variable FASTLANE_XCODEBUILD_SETTINGS_TIMEOUT, and the number of retries with the environment variable FASTLANE_XCODEBUILD_SETTINGS_RETRIES

解決辦法
通過日志描述,知道是超時了,這時候我們只需要在fastfile 文件頂部加上設(shè)置超時時長和超時嘗試次數(shù)的環(huán)境變量即可;
ENV["FASTLANE_XCODEBUILD_SETTINGS_TIMEOUT"] = "180"
ENV["FASTLANE_XCODEBUILD_SETTINGS_RETRIES"] = "10"