iOS開發(fā)fastlane從入門到入土(一):自動打包

fastlane

Fastlane是一套使用Ruby寫的自動化工具集,旨在簡化Android和iOS的部署過程,自動化你的工作流。它可以簡化一些乏味、單調(diào)、重復(fù)的工作,像截圖、代碼簽名以及發(fā)布App。命令一時爽,一直命令一直爽。當你發(fā)現(xiàn)可以隨心所欲的一行命令打包時,你就會發(fā)現(xiàn)fastlane有多爽了。

小插曲:之前用的2.117版本因為terminal-notifier版本過低導(dǎo)致本地通知無效的bug,就去提了issue,第三天就解決發(fā)布了新版本,效率真的高啊??
本文基于fastlane-2.118.0

一、Fastlane的安裝和初始化

  • 確保安裝最新的Xcode命令行工具
    xcode-select --install
  • 安裝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即可
    使用fastlane -v檢查是否安裝成功
  • 初始化fastlane
    cd到項目根目錄下輸入fastlane init
[?] Looking for iOS and Android projects in current directory...
[10:42:32]: Created new folder './fastlane'.
[10:42:32]: Detected an iOS/macOS project in the current directory: 'NearChargeCompany.xcworkspace'
[10:42:32]: -----------------------------
[10:42:32]: --- Welcome to fastlane ?? ---
[10:42:32]: -----------------------------
[10:42:32]: fastlane can help you with all kinds of automation for your mobile app
[10:42:32]: We recommend automating one task first, and then gradually automating more over time
[10:42:32]: What would you like to use fastlane for?
1. ??  Automate screenshots  --自動化截圖 (基于UITests)
2. ?????  Automate beta distribution to TestFlight --將測試版分發(fā)到TestFlight
3. ??  Automate App Store distribution --自動上傳、發(fā)布到App Store
4. ??  Manual setup - manually setup your project to automate your tasks --手動設(shè)置 - 手動設(shè)置您的項目以使您的任務(wù)自動化

這里我選擇“3”-發(fā)布到Appstore
輸入開發(fā)者賬號與密碼,如果開啟兩部驗證需要輸入安全碼

[10:54:25]: --------------------------------
[10:54:25]: --- Login with your Apple ID ---
[10:54:25]: --------------------------------
[10:54:25]: To use App Store Connect and Apple Developer Portal features as part of fastlane,
[10:54:25]: we will ask you for your Apple ID username and password
[10:54:25]: This is necessary for certain fastlane features, for example:
[10:54:25]: 
[10:54:25]: - Create and manage your provisioning profiles on the Developer Portal
[10:54:25]: - Upload and manage TestFlight and App Store builds on App Store Connect
[10:54:25]: - Manage your App Store Connect app metadata and screenshots
[10:54:25]: 
[10:54:25]: Your Apple ID credentials will only be stored in your Keychain, on your local machine
[10:54:25]: For more information, check out
[10:54:25]:     https://github.com/fastlane/fastlane/tree/master/credentials_manager
[10:54:25]: 
[10:54:25]: Please enter your Apple ID developer credentials
[10:54:25]: Apple ID Username:
xx@xxx.com
[10:55:29]: Logging in...
Available session is not valid any more. Continuing with normal login.
Two-factor Authentication (6 digits code) is enabled for account 'xx@xxx.com'
More information about Two-factor Authentication: https://support.apple.com/en-us/HT204915

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

(Input `sms` to escape this prompt and select a trusted phone number to send the code as a text message)
Please enter the 6 digit code:
260449
Requesting session...
[10:55:58]: ?  Logging in with your Apple ID was successful

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

[10:56:08]: Would you like fastlane to manage your app's metadata? (y/n)
y

這一步肯定會創(chuàng)建AppfileFastfile。如果Deliverfilescreenshotsmetadata目錄沒被創(chuàng)建,可以運行deliver init來創(chuàng)建。下載iTC上的截圖deliver download_screenshots,下載iTC上的元數(shù)據(jù) deliver download_metadata

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的文件配置

以下配置文件強烈建議默認使用Sublime Text工具打開,Sublime支持Ruby語法,方便注釋以及縮進等編輯

cd fastlane
open -a /Applications/Sublime\ Text.app/ Appfile Deliverfile Fastfile

1、配置.env

用于把賬號信息、更新描述、工程相關(guān)信息、證書文件等單獨放在一個配置文件,方便集中更改。
我們可以在fastlane下創(chuàng)建一個名為.env 的文件,自定義所需的臨時變量,然后Fastlane的三個配置文件(AppfileDeliverfileFastfile)分別從.env文件中通過ENV['xxxx']讀取配置信息。
首先創(chuàng)建一個.env文件

yangdeMacBook-Pro:NearChargeCompany yang$ cd fastlane
yangdeMacBook-Pro:fastlane yang$ ls -a
.       ..      Appfile     Deliverfile Fastfile    metadata    screenshots
yangdeMacBook-Pro:fastlane yang$ touch .env
yangdeMacBook-Pro:fastlane yang$ ls -a
.       .env        Deliverfile metadata
..      Appfile     Fastfile    screenshots

.env文件為隱藏文件,可使用如下命令查看:

$ defaults write com.apple.finder AppleShowAllFiles -boolean true;
$ killall Finder

以下是我的環(huán)境變量配置:

  #APP唯一標識符
  APP_IDENTIFIER = "com.xxx.xx"

  #蘋果開發(fā)者賬號
  APPLE_ID = "xx@xxx.com"
  
  #ADC Team ID
  TEAM_ID = "CN*****SEU"

  #ITC Team ID
  ITC_TEAM_ID = "11*****89"

  #設(shè)置shell的語言環(huán)境
  LANG = "en_US.UTF-8"
  LC_ALL = "en_US.UTF-8"

  #工程名稱
  SCHEME_NAME = "YourProjectName"

  #App 元數(shù)據(jù)及截圖存放路徑
  METADATA_PATH = "./metadata"
  SCREENSHOTS_PATH = "./screenshots"

  #ipa輸出文件夾路徑
  OUTPUT_DIRECTORY = "/Users/xx/Desktop/xxx/ipa"

  #App 元數(shù)據(jù)及截圖下載時 直接覆蓋 不詢問
  DELIER_FORCE_OVERWRITE= true

  #更新描述
  UPDATE_DESCRIPTION = "fastlane自動打包上傳測試"

  #自動提交審核
  SUBMIT_FOR_REVIEW = false

  #審核通過后立刻發(fā)布
  AUTOMATIC_RELEASE = false

  #PP文件
  PP_ADHOC = "xxxxxx_ADHoc"
  PP_APPSTORE = "xxxxxx_Distribution"

*注:ADC為開發(fā)者網(wǎng)站,ITC是ItunesConnect網(wǎng)站
關(guān)于ENV用法可以參考Environment Variables Doc

2、配置Appfile

Appfile文件用于指定 app_identifier, apple_id, team_id, itc_team_id等一些fastlane需要用到的信息.

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

*注:以上文件用到的數(shù)據(jù)均為從ENV環(huán)境變量中取得
Appfile的詳細用法可以參考Appfile Doc

3、配置Deliverfile

用于配置應(yīng)用在 ITC 中的元數(shù)據(jù)信息,優(yōu)先級高于編輯metadata文件夾下的文件。

# 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 "2019 xxx Inc"

# 支持語言
supportedLanguages = {
  "cmn-Hans" => "zh-Hans"
}

# app 名稱
# name({
# 'zh-Hans' => "APPDemo"
# })

# 副標題
# subtitle(
#   'zh-Hans' => "小魚小魚,蝦米蝦米"
# )

# App價格
#price_tier 0

# 應(yīng)用程序圖標的路徑 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
})

# # 應(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 ENV['SUBMIT_FOR_REVIEW']

# 審核通過后是否立刻發(fā)布,false表示需要手動發(fā)布
automatic_release ENV['AUTOMATIC_RELEASE']

Deliverfile的詳細配置可以參考Deliver Doc

4、配置Fastfile

fastlane 中的塊和lane

前面都是小打小鬧,接下來就要進入到Fastlane的核心部分了。我們打包、發(fā)布等操作都是通過這個文件來執(zhí)行。

Fastfile里面包含的塊類型有以下幾種:

  • before_all 用于執(zhí)行任務(wù)之前的操作,比如使用cocopods更新pod庫,只執(zhí)行一次
  • before_each 每次執(zhí)行 lane 之前都會執(zhí)行一次
  • lane 定義用戶的主要任務(wù)流程。例如打包ipa,執(zhí)行測試等等
  • after_each 每次執(zhí)行 lane 之后都會執(zhí)行一次
  • after_all 用于執(zhí)行任務(wù)之后的操作,比如發(fā)送郵件,通知之類的
  • error 在執(zhí)行上述情況任意環(huán)境報錯都會中止并執(zhí)行一次
    下面講解一下一個簡單的lane的組成
desc "打包上傳到AppStore"   //該任務(wù)的描述
lane :to_appStore do | options |  //定義名字為 to_appStore 的任務(wù),option用于接收我們的外部參數(shù),這里可以傳入?yún)?shù)
    customLane  //自定義的lane
    gym(workspace: "expample.xcworkspace", scheme: "example")  //構(gòu)建App
    deliver  //上傳到appstore
end

在控制臺進入項目所在的文件夾下面,執(zhí)行以下命令即可執(zhí)行任務(wù):

fastlane to_appStore

我們通俗的把一個lane理解為一個任務(wù),每個任務(wù)都負責(zé)一個功能。 然后我們調(diào)用不同的任務(wù),來實現(xiàn)打包、上傳到testFlight、上傳到app store等功能。 每個任務(wù)里可以調(diào)用其他的小任務(wù),可以理解為函數(shù),gym、deliver這些Action則是已經(jīng)給我們封裝好的函數(shù)。

fastlane 常用的工具集

工具 描述
scan 自動運行測試工具,并且可以生成漂亮的HTML報告
cert 自動創(chuàng)建和管理iOS簽名證書(Certificates)
sigh 創(chuàng)建、更新、下載、修復(fù)Provisioning Profiles的工具
pem 自動生成、更新推送配置文件
match 一個新的自動創(chuàng)建和管理iOS簽名證書和Provisioning Profiles工具(推薦團隊使用) ??
snapshot Xcode7推出的UI test功能實現(xiàn)自動化截圖
frameit 給截屏套上一層外邊框
gym 編譯打包生成ipa文件,又名build_ios_appbuild_app
produce 如果你的產(chǎn)品還沒在iTunes Connect(iTC)或者Apple Developer Center(ADC)建立,produce可以自動幫你完成這些工作
deliver 自動上傳截圖,APP的元數(shù)據(jù),二進制(ipa)文件到iTunes Connect
WatchBuild 一個獨立的iTC監(jiān)控工具,開啟WatchBuild可以監(jiān)控iTC上的文件狀態(tài),彈出MacOS自帶的Notification

更多工具集的使用可以參考fastlane actions Doc

恭喜你騷年,到目前為止,你已經(jīng)掌握了fastlane基本的用法,能夠完成基本的發(fā)包等操作了。接下來就是要講到插件、自動截圖(基于UI Test)以及證書的管理等進階用法了。

由于fastlane是由Ruby寫的,如果想自己實現(xiàn)更多騷操作,可以參考Ruby語法教程。
更多關(guān)于Fastfile用法可以參考Fastfile Doc

三、Fastlane插件管理

Fastlane的插件是一個或者一組action的打包,單獨發(fā)布在fastlane之外。

查找插件

使用fastlane search_plugins查找所有插件,使用fastlane search_plugins [query]查找指定插件

$ fastlane search_plugins pgyer
...
+----------------+----------------------+-----------+
|             fastlane plugins 'pgyer'              |
+----------------+----------------------+-----------+
| Name           | Description          | Downloads |
+----------------+----------------------+-----------+
| pgyer          | distribute app to    | 18497     |
|                | pgyer beta testing   |           |
|                | service              |           |
| pgyer-password | distribute app to    | 1065      |
|                | pgyer beta testing   |           |
|                | service              |           |
| ding_talk      | Auto send the pgyer  | 659       |
|                | app qr code to the   |           |
|                | ding talk.           |           |
+----------------+----------------------+-----------+

安裝插件

使用fastlane add_plugin [name]安裝插件
下面會用到的兩個插件:

  • fastlane-plugin-versioning:用來修改build版本號和version版本號。
  • fastlane-plugin-pgyer:用來上傳ipa包到蒲公英。
$fastlane add_plugin pgyer
[10:46:46]: Get started using a Gemfile for fastlane https://docs.fastlane.tools/getting-started/ios/setup/#use-a-gemfile
[10:46:47]: Plugin 'fastlane-plugin-pgyer' was added to './fastlane/Pluginfile'
[10:46:47]: It looks like fastlane plugins are not yet set up for this project.
[10:46:47]: fastlane will modify your existing Gemfile at path '../Gemfile'
[10:46:47]: This change is necessary for fastlane plugins to work
[10:46:47]: Should fastlane modify the Gemfile at path
'../Gemfile' for you?
(y/n)
y
[10:46:56]: Successfully modified '../Gemfile'
[10:46:56]: Make sure to commit your Gemfile, Gemfile.lock and Pluginfile to version control
Installing plugin dependencies...
Successfully installed plugins

安裝成功后在fastlane目錄下會多出一個.Pluginfile文件

# Autogenerated by fastlane
#
# Ensure this file is checked in to source control!

gem 'fastlane-plugin-pgyer'
gem 'fastlane-plugin-versioning' //刪除這一行就是刪除了此插件

*附:上傳蒲公英需要去蒲公英的賬戶設(shè)置里獲取到API信息

插件使用方法

使用fastlane action查找某個action的使用方法和參數(shù)

$ fastlane action pgyer
Loading documentation for pgyer:
+------------------+------------------+------------------+---------+
|                          pgyer Options                           |
+------------------+------------------+------------------+---------+
| Key              | Description      | Env Var          | Default |
+------------------+------------------+------------------+---------+
| api_key          | api_key in your  | PGYER_API_KEY    |         |
|                  | pgyer account    |                  |         |
| user_key         | user_key in      | PGYER_USER_KEY   |         |
|                  | your pgyer       |                  |         |
|                  | account          |                  |         |
| apk              | Path to your     | PGYER_APK        |         |
|                  | APK file         |                  |         |
| ipa              | Path to your     | PGYER_IPA        |         |
|                  | IPA file.        |                  |         |
|                  | Optional if you  |                  |         |
|                  | use the _gym_    |                  |         |
|                  | or _xcodebuild_  |                  |         |
|                  | action. For Mac  |                  |         |
|                  | zip the .app.    |                  |         |
|                  | For Android      |                  |         |
|                  | provide path to  |                  |         |
|                  | .apk file        |                  |         |
| password         | set password to  | PGYER_PASSWORD   |         |
|                  | protect app      |                  |         |
| update_descript  | set update       | PGYER_UPDATE_DE  |         |
| ion              | description for  | SCRIPTION        |         |
|                  | app              |                  |         |
| install_type     | set install      | PGYER_INSTALL_T  |         |
|                  | type for app     | YPE              |         |
|                  | (1=public,       |                  |         |
|                  | 2=password,      |                  |         |
|                  | 3=invite).       |                  |         |
|                  | Please set as a  |                  |         |
|                  | string           |                  |         |
+------------------+------------------+------------------+---------+
* = default value is dependent on the user's system

More information can be found on https://docs.fastlane.tools/actions/pgyer

更多插件的使用可以參考Plugins Doc

四、實戰(zhàn)環(huán)節(jié)


上面說了那么多,是時候展現(xiàn)真正的技術(shù)了少年。以下是我的一份自動打包的文件,其中有相關(guān)action的相關(guān)注釋。
如果在提交過程中遇到兩步驗證,請參考兩步驗證處理方法

# 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ù),小寫、_開頭為變量,$開頭為全局變量(直接用#訪問)
# scheme名
SCHEME_NAME = ENV['SCHEME_NAME']

# workspace名
WORKSPACE_NAME = "#{SCHEME_NAME}.xcworkspace"

# Bundle ID
APP_IDENTIFIER = ENV['APP_IDENTIFIER']

# app名
APP_NAME = 'FastLaneDemo'

# 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

# 蒲公英 api_key user_key
PGYER_API_KEY = 'xxxxxxx'
PGYER_USER_KEY = 'xxxxxxx'
  
platform :ios do
  before_all do
    # 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:打包adHoc上傳蒲公英  3:打包Inhouse上傳蒲公英  0:結(jié)束打包  回車表示使用默認打包\033[0m"
      select_method = STDIN.gets.chomp
      if select_method!='1' && select_method!='2' && select_method!='3' && !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 "當前工程的版本號是:\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 "請輸入版本號,回車表示使用當前版本號\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'
        puts "發(fā)布到蒲公英"
        # 打包adhoc發(fā)布到蒲公英
        release_adhoc(options)
      when '3'
        # 打包inhouse發(fā)布到蒲公英
        
      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ā)布ad-hoc"
  lane :release_adhoc do |options|
    options[:export_method] = "ad-hoc"
    prepare(options)
    build(options)
    deliver_pgyer
  end

  desc "發(fā)布企業(yè)Inhouse"
  lane :release_enterprise do |options|
    options[:export_method] = "enterprise"
    prepare(options)
    build(options)
  end

  desc "上傳到蒲公英"
  lane :deliver_pgyer do |options|
    pgyer( 
       api_key: PGYER_API_KEY, # 從蒲公英項目詳情中獲取的apikey
       user_key: PGYER_USER_KEY, # 從蒲公英項目詳情中獲取的 userkey
       ipa: $IPA_PATH, #ipa包路徑
       #password: "123456", #設(shè)置安裝密碼
       #install_type: "2", #1:公開,2:密碼安裝,3:邀請安裝,4:回答問題安裝。默認為1公開
       update_description: 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' => "這是第一個版本哦"
       },
       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/Pgyer/#{SCHEME_NAME}-#{build_time}"
    when 'enterprise'
       provisioningProfiles = ENV['PP_ENTERPRISE']
       outputDir = "#$OUTPUT_DIRECTORY/Pgyer/#{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: {  # 指定pp文件
          "#{APP_IDENTIFIER}" => "#{provisioningProfiles}"
        },
        signingStyle: "manual" # 手動簽名
       }
    )
  end

  desc "新創(chuàng)建一個app"
  lane :create_app do
?    produce(
        username: 'test@qq.com',
        app_identifier: 'com.company.TestProject',
        app_name: '測試工程',
        language: 'Simplified Chinese',
        app_version: '1.0',
        sku: '123', # 注意,sku必須大于2個字符
        team_name: 'DNxxxx', # only necessary when in multiple teams
        #如果只在AppleDeveloper創(chuàng)建app,不在iTunesConnect創(chuàng)建app的話
        #skip_itc: true,

        # Optional
        # App services can be enabled during app creation
        enable_services: {
          # access_wifi: "on",             # Valid values: "on", "off"
          # app_group: "on",               # Valid values: "on", "off"
          # apple_pay: "on",               # Valid values: "on", "off"
          # associated_domains: "on",      # Valid values: "on", "off"
          # auto_fill_credential: "on",    # Valid values: "on", "off"
          # data_protection: "complete",   # Valid values: "complete", "unlessopen", "untilfirstauth",
          # game_center: "on",             # Valid values: "on", "off"
          # health_kit: "on",              # Valid values: "on", "off"
          # home_kit: "on",                # Valid values: "on", "off"
          # hotspot: "on",                 # Valid values: "on", "off"
          # icloud: "cloudkit",            # Valid values: "legacy", "cloudkit"
          # in_app_purchase: "on",         # Valid values: "on", "off"
          # inter_app_audio: "on",         # Valid values: "on", "off"
          # passbook: "on",                # Valid values: "on", "off"
          # multipath: "on",               # Valid values: "on", "off"
          # network_extension: "on",       # Valid values: "on", "off"
          # nfc_tag_reading: "on",         # Valid values: "on", "off"
          # personal_vpn: "on",            # Valid values: "on", "off"
          # passbook: "on",                # Valid values: "on", "off" (deprecated)
          # siri_kit: "on",                # Valid values: "on", "off"
          # vpn_configuration: "on",       # Valid values: "on", "off" (deprecated)
          # wallet: "on",                  # Valid values: "on", "off"
          # wireless_accessory: "on",      # Valid values: "on", "off"
          push_notification: "on",       # Valid values: "on", "off"
        }
    )
  end

  after_all do |lane|
    #slack(
    #   message: "Successfully deployed new App Update."
    #)
  end

  error do |lane, exception|
     #slack(
     #  message: exception.message,
     #  success: false
     #)
  end

end

配置好Fastfile后cd到工程目錄下,調(diào)用fastlane release實現(xiàn)自動打包。

Couldn't find specified scheme 'YourScheme'. Please make sure that the scheme is shared, see ...

如果發(fā)現(xiàn)出現(xiàn)上面的錯誤,請勾選scheme的Shared。


未完待續(xù)

本篇只是簡單的寫了關(guān)于Fastlane的安裝配置以及自動打包發(fā)布的流程,由于篇幅有限,很多其他的功能未能詳細說明,后續(xù)我會補上自動截圖、證書管理、釘釘通知以及上傳dSYM到Bugly等功能。


后續(xù)文章更新啦~
iOS開發(fā)fastlane從入門到入土(二):自動截屏
iOS開發(fā)fastlane從入門到入土(三):證書管理

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 227,748評論 6 531
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 98,165評論 3 414
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 175,595評論 0 373
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經(jīng)常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,633評論 1 309
  • 正文 為了忘掉前任,我火速辦了婚禮,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,435評論 6 405
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 54,943評論 1 321
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,035評論 3 440
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 42,175評論 0 287
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 48,713評論 1 333
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 40,599評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,788評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,303評論 5 358
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 44,034評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,412評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,664評論 1 280
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,408評論 3 390
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,747評論 2 370

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